idx int64 1 56k | question stringlengths 15 155 | answer stringlengths 2 29.2k ⌀ | question_cut stringlengths 15 100 | answer_cut stringlengths 2 200 ⌀ | conversation stringlengths 47 29.3k | conversation_cut stringlengths 47 301 |
|---|---|---|---|---|---|---|
17,401 | Which statistical classification algorithm can predict true/false for a sequence of inputs? | I would suggest that you define some features, and then pick a machine learning algorithm to apply to those features.
Features: Basically, each feature should be something that can be computed from a particular sequence, and that you think may be relevant to whether the sequence has the property or not. Based upon your description, you might consider features such as the following:
"Bag of numbers". You might count how many times each possible number appears in the sequence. For instance, suppose each sequence is made out of the numbers 1-30 only. Then you can generate 30 features; the $i$th feature counts how many times the number $i$ appears in the sequence. For instance, the sequence (7 5 21 3 3) generates the feature vector (0,0,2,0,1,0,1,0,...,0,1,0,...,0).
"Bag of digrams." A digram is a pair of consecutive numbers. Given a sequence, you can extract all of its digrams. Then you could count how many times each possible digram appears. For instance, the sequence (7 5 21 3 3) has the following as its digrams: 7 5, 5 21, 21 3, and 3 3. Assuming the sequence is made out of the numbers 1-30, there are $30^2$ possible digrams, so you obtain $30^2$ features. Given a sequence, you can generate this feature vector.
"Bag of trigrams." You could also consider trigrams, which is a subsequence of three consecutive numbers from the original sequence. You can do the same as above.
If you use the above features, you can then extract $d=30+30^2+30^3$ features from each sequence. In other words, to each sequence, you associate a $d$-dimensional feature vector, which is the collection of features. Once you have this, you can throw away the original sequences. For instance, your training set becomes a bunch of input/output-pairs, where the input is the feature vector (corresponding to some sequence from your training set) and the output is a boolean (indicating whether that sequence had the property or not).
Another variation on the above idea is to use "set of X" instead of "bag of X". For instance, instead of counting how many times each number $i$ appears, you could simply generate a boolean that indicates whether the number $i$ has appeared at least once or not. This may or may not give better results. In general, you can experiment with the set of features you use, to figure out which ones give the best results (for instance, maybe you drop the "bag of trigrams"; or maybe you can come up with some other ideas to try).
Machine learning algorithm: I'm not qualified to give you advice about how to select a machine learning algorithm; there are many possibilities. But in general you are going to apply the learning algorithm to your training set (the input/output pairs of features/booleans), and try to use it to predict which of the values in the test set have the property. Your selection of machine learning algorithm may depend upon several factors, including how the size of the training set compares relative to $d$ (the number of features). Your best bet may be to try several machine learning algorithms and see which works the best. You might want to include Support Vector Machines (SVMs) as one of the algorithms you try. | Which statistical classification algorithm can predict true/false for a sequence of inputs? | I would suggest that you define some features, and then pick a machine learning algorithm to apply to those features.
Features: Basically, each feature should be something that can be computed from a | Which statistical classification algorithm can predict true/false for a sequence of inputs?
I would suggest that you define some features, and then pick a machine learning algorithm to apply to those features.
Features: Basically, each feature should be something that can be computed from a particular sequence, and that you think may be relevant to whether the sequence has the property or not. Based upon your description, you might consider features such as the following:
"Bag of numbers". You might count how many times each possible number appears in the sequence. For instance, suppose each sequence is made out of the numbers 1-30 only. Then you can generate 30 features; the $i$th feature counts how many times the number $i$ appears in the sequence. For instance, the sequence (7 5 21 3 3) generates the feature vector (0,0,2,0,1,0,1,0,...,0,1,0,...,0).
"Bag of digrams." A digram is a pair of consecutive numbers. Given a sequence, you can extract all of its digrams. Then you could count how many times each possible digram appears. For instance, the sequence (7 5 21 3 3) has the following as its digrams: 7 5, 5 21, 21 3, and 3 3. Assuming the sequence is made out of the numbers 1-30, there are $30^2$ possible digrams, so you obtain $30^2$ features. Given a sequence, you can generate this feature vector.
"Bag of trigrams." You could also consider trigrams, which is a subsequence of three consecutive numbers from the original sequence. You can do the same as above.
If you use the above features, you can then extract $d=30+30^2+30^3$ features from each sequence. In other words, to each sequence, you associate a $d$-dimensional feature vector, which is the collection of features. Once you have this, you can throw away the original sequences. For instance, your training set becomes a bunch of input/output-pairs, where the input is the feature vector (corresponding to some sequence from your training set) and the output is a boolean (indicating whether that sequence had the property or not).
Another variation on the above idea is to use "set of X" instead of "bag of X". For instance, instead of counting how many times each number $i$ appears, you could simply generate a boolean that indicates whether the number $i$ has appeared at least once or not. This may or may not give better results. In general, you can experiment with the set of features you use, to figure out which ones give the best results (for instance, maybe you drop the "bag of trigrams"; or maybe you can come up with some other ideas to try).
Machine learning algorithm: I'm not qualified to give you advice about how to select a machine learning algorithm; there are many possibilities. But in general you are going to apply the learning algorithm to your training set (the input/output pairs of features/booleans), and try to use it to predict which of the values in the test set have the property. Your selection of machine learning algorithm may depend upon several factors, including how the size of the training set compares relative to $d$ (the number of features). Your best bet may be to try several machine learning algorithms and see which works the best. You might want to include Support Vector Machines (SVMs) as one of the algorithms you try. | Which statistical classification algorithm can predict true/false for a sequence of inputs?
I would suggest that you define some features, and then pick a machine learning algorithm to apply to those features.
Features: Basically, each feature should be something that can be computed from a |
17,402 | Which statistical classification algorithm can predict true/false for a sequence of inputs? | What you're effectively doing is hypothesis testing on time series. HMMs would work for you, though you would have to adapt them to your particular case.
Honestly, if you can't write down some kind of mathematical description of what you're trying to detect, you're not going to get very far. Perhaps you can tell us about what kind of feature you're expecting to see? | Which statistical classification algorithm can predict true/false for a sequence of inputs? | What you're effectively doing is hypothesis testing on time series. HMMs would work for you, though you would have to adapt them to your particular case.
Honestly, if you can't write down some kind of | Which statistical classification algorithm can predict true/false for a sequence of inputs?
What you're effectively doing is hypothesis testing on time series. HMMs would work for you, though you would have to adapt them to your particular case.
Honestly, if you can't write down some kind of mathematical description of what you're trying to detect, you're not going to get very far. Perhaps you can tell us about what kind of feature you're expecting to see? | Which statistical classification algorithm can predict true/false for a sequence of inputs?
What you're effectively doing is hypothesis testing on time series. HMMs would work for you, though you would have to adapt them to your particular case.
Honestly, if you can't write down some kind of |
17,403 | Which statistical classification algorithm can predict true/false for a sequence of inputs? | Given a max length of 12 on the sequence, then a neural network with 12 inputs and one output may work, but you would have to pad the end of each sequence with zeroes or some inert value. | Which statistical classification algorithm can predict true/false for a sequence of inputs? | Given a max length of 12 on the sequence, then a neural network with 12 inputs and one output may work, but you would have to pad the end of each sequence with zeroes or some inert value. | Which statistical classification algorithm can predict true/false for a sequence of inputs?
Given a max length of 12 on the sequence, then a neural network with 12 inputs and one output may work, but you would have to pad the end of each sequence with zeroes or some inert value. | Which statistical classification algorithm can predict true/false for a sequence of inputs?
Given a max length of 12 on the sequence, then a neural network with 12 inputs and one output may work, but you would have to pad the end of each sequence with zeroes or some inert value. |
17,404 | Which statistical classification algorithm can predict true/false for a sequence of inputs? | Have you tried using Bayesian networks? That's the first thing I think of when I need to fuse multiple pieces of data (coming in one at a time) to arrive at the probabilities of a random variable.
Bayesian networks don't rely on the independence assumption that naive Bayes does.
BTW, hidden Markov models are a special case of Bayesian networks. | Which statistical classification algorithm can predict true/false for a sequence of inputs? | Have you tried using Bayesian networks? That's the first thing I think of when I need to fuse multiple pieces of data (coming in one at a time) to arrive at the probabilities of a random variable.
Bay | Which statistical classification algorithm can predict true/false for a sequence of inputs?
Have you tried using Bayesian networks? That's the first thing I think of when I need to fuse multiple pieces of data (coming in one at a time) to arrive at the probabilities of a random variable.
Bayesian networks don't rely on the independence assumption that naive Bayes does.
BTW, hidden Markov models are a special case of Bayesian networks. | Which statistical classification algorithm can predict true/false for a sequence of inputs?
Have you tried using Bayesian networks? That's the first thing I think of when I need to fuse multiple pieces of data (coming in one at a time) to arrive at the probabilities of a random variable.
Bay |
17,405 | How to do piecewise linear regression with multiple unknown knots? | Would MARS be applicable? R has the package earth that implements it. | How to do piecewise linear regression with multiple unknown knots? | Would MARS be applicable? R has the package earth that implements it. | How to do piecewise linear regression with multiple unknown knots?
Would MARS be applicable? R has the package earth that implements it. | How to do piecewise linear regression with multiple unknown knots?
Would MARS be applicable? R has the package earth that implements it. |
17,406 | How to do piecewise linear regression with multiple unknown knots? | In general, it's a bit odd to want to fit something as piece-wise linear. However, if you really wish to do so, then the MARS algorithm is the most direct. It will build up a function one knot at a time; and then usually prunes back the number of knots to combat over-fitting ala decision trees. You can access the MARS algotithm in R via earth or mda. In general, it's fit with GCV which is not so far removed from the other information criterion (AIC, BIC etc.)
MARS won't really give you an "optimal" fit since the knots are grown one at a time. It really would be rather difficult to fit a truly "optimal" number of knots since the possible permutations of knot placements would quickly explode.
Generally, this is why people turn towards smoothing splines. Most smoothing splines are cubic just so you can fool a human eye into missing the discontinuities. It would be quite possible to do a linear smoothing spline however. The big advantage of smoothing splines are their single parameter to optimize. That allows you to quickly reach a truly "optimal" solution without having to search through gobs of permutations. However, if you really want to seek inflection points, and you have enough data to do so, then something like MARS would probably be your best bet.
Here's some example code for penalized linear smoothing splines in R:
require(mgcv);data(iris);
gam.test <- gam(Sepal.Length ~ s(Petal.Width,k=6,bs='ps',m=0),data=iris)
summary(gam.test);plot(gam.test);
The actual knots chosen would not necessarily correlate with any true inflection points however. | How to do piecewise linear regression with multiple unknown knots? | In general, it's a bit odd to want to fit something as piece-wise linear. However, if you really wish to do so, then the MARS algorithm is the most direct. It will build up a function one knot at a | How to do piecewise linear regression with multiple unknown knots?
In general, it's a bit odd to want to fit something as piece-wise linear. However, if you really wish to do so, then the MARS algorithm is the most direct. It will build up a function one knot at a time; and then usually prunes back the number of knots to combat over-fitting ala decision trees. You can access the MARS algotithm in R via earth or mda. In general, it's fit with GCV which is not so far removed from the other information criterion (AIC, BIC etc.)
MARS won't really give you an "optimal" fit since the knots are grown one at a time. It really would be rather difficult to fit a truly "optimal" number of knots since the possible permutations of knot placements would quickly explode.
Generally, this is why people turn towards smoothing splines. Most smoothing splines are cubic just so you can fool a human eye into missing the discontinuities. It would be quite possible to do a linear smoothing spline however. The big advantage of smoothing splines are their single parameter to optimize. That allows you to quickly reach a truly "optimal" solution without having to search through gobs of permutations. However, if you really want to seek inflection points, and you have enough data to do so, then something like MARS would probably be your best bet.
Here's some example code for penalized linear smoothing splines in R:
require(mgcv);data(iris);
gam.test <- gam(Sepal.Length ~ s(Petal.Width,k=6,bs='ps',m=0),data=iris)
summary(gam.test);plot(gam.test);
The actual knots chosen would not necessarily correlate with any true inflection points however. | How to do piecewise linear regression with multiple unknown knots?
In general, it's a bit odd to want to fit something as piece-wise linear. However, if you really wish to do so, then the MARS algorithm is the most direct. It will build up a function one knot at a |
17,407 | How to do piecewise linear regression with multiple unknown knots? | I have programmed this from scratch once a few years ago, and I have a Matlab file for doing piece-wise linear regression on my computer. About 1 to 4 breakpoints is computationally possible for about 20 measurements points or so. 5 or 7 break points starts to be really too much.
The pure mathematical approach as I see it is to try all possible combinations as suggested by user mbq in the question linked to in the comment below your question.
Since the fitted lines are all consecutive and adjacent (no overlaps) the combinatorics will follow Pascals triangle. If there were overlaps between used data points by the line segments I believe that the combinatorics would follow Stirling numbers of the second kind instead.
The best solution in my mind is to choose the combination of fitted lines that has the lowest standard deviation of the R^2 correlation values of the fitted lines. I will try to explain with an example. Keep in mind though that asking how many break points one should find in the data, is similar to asking the question "How long is the coast of Britain?" as in one of Benoit Mandelbrots (a mathematician) papers about fractals. And there is a trade-off between number of break points and regression depth.
Now to the example.
Suppose we have the perfect data $y$ as a function of $x$ ($x$ and $y$ are integers):
$$\begin{array}{|c|c|c|c|c|c|}
\hline &x &y &R^2 line 1 &R^2 line 2 &sum of R^2 values &standard deviation of R^2 \\
\hline &1 &1 &1,000 &0,0400 &1,0400 &0,6788 \\
\hline &2 &2 &1,000 &0,0118 &1,0118 &0,6987 \\
\hline &3 &3 &1,000 &0,0004 &1,0004 &0,7067 \\
\hline &4 &4 &1,000 &0,0031 &1,0031 &0,7048 \\
\hline &5 &5 &1,000 &0,0135 &1,0135 &0,6974 \\
\hline &6 &6 &1,000 &0,0238 &1,0238 &0,6902 \\
\hline &7 &7 &1,000 &0,0277 &1,0277 &0,6874 \\
\hline &8 &8 &1,000 &0,0222 &1,0222 &0,6913 \\
\hline &9 &9 &1,000 &0,0093 &1,0093 &0,7004 \\
\hline &10 &10 &1,000 &-1,978 &1,000 &0,7071 \\
\hline &11 &9 &0,9709 &0,0271 &0,9980 &0,6673 \\
\hline &12 &8 &0,8951 &0,1139 &1,0090 &0,5523 \\
\hline &13 &7 &0,7734 &0,2558 &1,0292 &0,3659 \\
\hline &14 &6 &0,6134 &0,4321 &1,0455 &0,1281 \\
\hline &15 &5 &0,4321 &0,6134 &1,0455 &0,1282 \\
\hline &16 &4 &0,2558 &0,7733 &1,0291 &0,3659 \\
\hline &17 &3 &0,1139 &0,8951 &1,0090 &0,5523 \\
\hline &18 &2 &0,0272 &0,9708 &0,9980 &0,6672 \\
\hline &19 &1 &0 &1,000 &1,000 &0,7071 \\
\hline &20 &2 &0,0094 &1,000 &1,0094 &0,7004 \\
\hline &21 &3 &0,0222 &1,000 &1,0222 &0,6914 \\
\hline &22 &4 &0,0278 &1,000 &1,0278 &0,6874 \\
\hline &23 &5 &0,0239 &1,000 &1,0239 &0,6902 \\
\hline &24 &6 &0,0136 &1,000 &1,0136 &0,6974 \\
\hline &25 &7 &0,0032 &1,000 &1,0032 &0,7048 \\
\hline &26 &8 &0,0004 &1,000 &1,0004 &0,7068 \\
\hline &27 &9 &0,0118 &1,000 &1,0118 &0,6987 \\
\hline &28 &10 &0,04 &1,000 &1,04 &0,6788 \\
\hline \end{array}$$
These y values have the graph:
Which clearly has two break points. For the sake of argument we will calculate the R^2 correlation values (with the Excel cell formulas (European dot-comma style)):
=INDEX(LINEST(B1:$B$1;A1:$A$1;TRUE;TRUE);3;1)
=INDEX(LINEST(B1:$B$28;A1:$A$28;TRUE;TRUE);3;1)
for all possible non-overlapping combinations of two fitted lines. All the possible pairs of R^2 values have the graph:
The question is which pair of R^2 values should we choose, and how do we generalize to multiple break points as asked in the title? One choice is to pick the combination for which the sum of the R-square correlation is the highest. Plotting this we get the upper blue curve below:
The blue curve, the sum of the R-squared values, is the highest in the middle. This is more clearly visible from the table with the value $1,0455$ as the highest value.
However it is my opinion that the minimum of the red curve is more accurate. That is, the minimum of the standard deviation of the R^2 values of the fitted regression lines should be the best choice.
Piece wise linear regression - Matlab - multiple break points | How to do piecewise linear regression with multiple unknown knots? | I have programmed this from scratch once a few years ago, and I have a Matlab file for doing piece-wise linear regression on my computer. About 1 to 4 breakpoints is computationally possible for about | How to do piecewise linear regression with multiple unknown knots?
I have programmed this from scratch once a few years ago, and I have a Matlab file for doing piece-wise linear regression on my computer. About 1 to 4 breakpoints is computationally possible for about 20 measurements points or so. 5 or 7 break points starts to be really too much.
The pure mathematical approach as I see it is to try all possible combinations as suggested by user mbq in the question linked to in the comment below your question.
Since the fitted lines are all consecutive and adjacent (no overlaps) the combinatorics will follow Pascals triangle. If there were overlaps between used data points by the line segments I believe that the combinatorics would follow Stirling numbers of the second kind instead.
The best solution in my mind is to choose the combination of fitted lines that has the lowest standard deviation of the R^2 correlation values of the fitted lines. I will try to explain with an example. Keep in mind though that asking how many break points one should find in the data, is similar to asking the question "How long is the coast of Britain?" as in one of Benoit Mandelbrots (a mathematician) papers about fractals. And there is a trade-off between number of break points and regression depth.
Now to the example.
Suppose we have the perfect data $y$ as a function of $x$ ($x$ and $y$ are integers):
$$\begin{array}{|c|c|c|c|c|c|}
\hline &x &y &R^2 line 1 &R^2 line 2 &sum of R^2 values &standard deviation of R^2 \\
\hline &1 &1 &1,000 &0,0400 &1,0400 &0,6788 \\
\hline &2 &2 &1,000 &0,0118 &1,0118 &0,6987 \\
\hline &3 &3 &1,000 &0,0004 &1,0004 &0,7067 \\
\hline &4 &4 &1,000 &0,0031 &1,0031 &0,7048 \\
\hline &5 &5 &1,000 &0,0135 &1,0135 &0,6974 \\
\hline &6 &6 &1,000 &0,0238 &1,0238 &0,6902 \\
\hline &7 &7 &1,000 &0,0277 &1,0277 &0,6874 \\
\hline &8 &8 &1,000 &0,0222 &1,0222 &0,6913 \\
\hline &9 &9 &1,000 &0,0093 &1,0093 &0,7004 \\
\hline &10 &10 &1,000 &-1,978 &1,000 &0,7071 \\
\hline &11 &9 &0,9709 &0,0271 &0,9980 &0,6673 \\
\hline &12 &8 &0,8951 &0,1139 &1,0090 &0,5523 \\
\hline &13 &7 &0,7734 &0,2558 &1,0292 &0,3659 \\
\hline &14 &6 &0,6134 &0,4321 &1,0455 &0,1281 \\
\hline &15 &5 &0,4321 &0,6134 &1,0455 &0,1282 \\
\hline &16 &4 &0,2558 &0,7733 &1,0291 &0,3659 \\
\hline &17 &3 &0,1139 &0,8951 &1,0090 &0,5523 \\
\hline &18 &2 &0,0272 &0,9708 &0,9980 &0,6672 \\
\hline &19 &1 &0 &1,000 &1,000 &0,7071 \\
\hline &20 &2 &0,0094 &1,000 &1,0094 &0,7004 \\
\hline &21 &3 &0,0222 &1,000 &1,0222 &0,6914 \\
\hline &22 &4 &0,0278 &1,000 &1,0278 &0,6874 \\
\hline &23 &5 &0,0239 &1,000 &1,0239 &0,6902 \\
\hline &24 &6 &0,0136 &1,000 &1,0136 &0,6974 \\
\hline &25 &7 &0,0032 &1,000 &1,0032 &0,7048 \\
\hline &26 &8 &0,0004 &1,000 &1,0004 &0,7068 \\
\hline &27 &9 &0,0118 &1,000 &1,0118 &0,6987 \\
\hline &28 &10 &0,04 &1,000 &1,04 &0,6788 \\
\hline \end{array}$$
These y values have the graph:
Which clearly has two break points. For the sake of argument we will calculate the R^2 correlation values (with the Excel cell formulas (European dot-comma style)):
=INDEX(LINEST(B1:$B$1;A1:$A$1;TRUE;TRUE);3;1)
=INDEX(LINEST(B1:$B$28;A1:$A$28;TRUE;TRUE);3;1)
for all possible non-overlapping combinations of two fitted lines. All the possible pairs of R^2 values have the graph:
The question is which pair of R^2 values should we choose, and how do we generalize to multiple break points as asked in the title? One choice is to pick the combination for which the sum of the R-square correlation is the highest. Plotting this we get the upper blue curve below:
The blue curve, the sum of the R-squared values, is the highest in the middle. This is more clearly visible from the table with the value $1,0455$ as the highest value.
However it is my opinion that the minimum of the red curve is more accurate. That is, the minimum of the standard deviation of the R^2 values of the fitted regression lines should be the best choice.
Piece wise linear regression - Matlab - multiple break points | How to do piecewise linear regression with multiple unknown knots?
I have programmed this from scratch once a few years ago, and I have a Matlab file for doing piece-wise linear regression on my computer. About 1 to 4 breakpoints is computationally possible for about |
17,408 | How to do piecewise linear regression with multiple unknown knots? | There is a pretty nice algorithm described in Tomé and Miranda (1984).
The proposed methodology uses a least-squares approach to compute the best continuous set of straight lines that fit a given time series, subject to a number of constraints on the minimum distance between breakpoints and on the minimum trend change at each breakpoint.
The code and a GUI are available in both Fortran and IDL from their website:
http://www.dfisica.ubi.pt/~artome/linearstep.html | How to do piecewise linear regression with multiple unknown knots? | There is a pretty nice algorithm described in Tomé and Miranda (1984).
The proposed methodology uses a least-squares approach to compute the best continuous set of straight lines that fit a given ti | How to do piecewise linear regression with multiple unknown knots?
There is a pretty nice algorithm described in Tomé and Miranda (1984).
The proposed methodology uses a least-squares approach to compute the best continuous set of straight lines that fit a given time series, subject to a number of constraints on the minimum distance between breakpoints and on the minimum trend change at each breakpoint.
The code and a GUI are available in both Fortran and IDL from their website:
http://www.dfisica.ubi.pt/~artome/linearstep.html | How to do piecewise linear regression with multiple unknown knots?
There is a pretty nice algorithm described in Tomé and Miranda (1984).
The proposed methodology uses a least-squares approach to compute the best continuous set of straight lines that fit a given ti |
17,409 | How to do piecewise linear regression with multiple unknown knots? | ... first of all you must to do it by iterations, and under some informative criterion, like AIC AICc BIC Cp; because you can get an "ideal" fit, if number of knots K = number od data points N, ok.
... first put K = 0; estimate L = K + 1 regressions, calculate AICc, for instance;
then assume minimal number of data points at a separate segment, say L = 3 or L = 4, ok
... put K = 1; start from L-th data as the first knot, calculate SS or MLE, ... and step by step the next data point as a knot, SS or MLE, up to the last knot at the N - L data; choose the arrangement with the best fit (SS or MLE) calculate AICc ...
... put K = 2; ... use all previous regressions (that is their SS or MLE), but step by step divide a single segment into all possible parts ... choose the arrangement with the best fit (SS or MLE) calculate AICc ... if the last AICc occurs greater then the previous one: stop the iterations ! This is an optimal solution under AICc criterion, ok | How to do piecewise linear regression with multiple unknown knots? | ... first of all you must to do it by iterations, and under some informative criterion, like AIC AICc BIC Cp; because you can get an "ideal" fit, if number of knots K = number od data points N, ok.
| How to do piecewise linear regression with multiple unknown knots?
... first of all you must to do it by iterations, and under some informative criterion, like AIC AICc BIC Cp; because you can get an "ideal" fit, if number of knots K = number od data points N, ok.
... first put K = 0; estimate L = K + 1 regressions, calculate AICc, for instance;
then assume minimal number of data points at a separate segment, say L = 3 or L = 4, ok
... put K = 1; start from L-th data as the first knot, calculate SS or MLE, ... and step by step the next data point as a knot, SS or MLE, up to the last knot at the N - L data; choose the arrangement with the best fit (SS or MLE) calculate AICc ...
... put K = 2; ... use all previous regressions (that is their SS or MLE), but step by step divide a single segment into all possible parts ... choose the arrangement with the best fit (SS or MLE) calculate AICc ... if the last AICc occurs greater then the previous one: stop the iterations ! This is an optimal solution under AICc criterion, ok | How to do piecewise linear regression with multiple unknown knots?
... first of all you must to do it by iterations, and under some informative criterion, like AIC AICc BIC Cp; because you can get an "ideal" fit, if number of knots K = number od data points N, ok.
|
17,410 | How to do piecewise linear regression with multiple unknown knots? | I once came across a program called Joinpoint. On their website they say it fits a joinpoint model where "several different lines are connected together at the 'joinpoints'". And further: "The user supplies the minimum and maximum number of joinpoints. The program starts with the minimum number of joinpoint (e.g. 0 joinpoints, which is a straight line) and tests whether more joinpoints are statistically significant and must be added to the model (up to that maximum number)."
The NCI uses it for trend modelling of cancer rates, maybe it fits your needs as well. | How to do piecewise linear regression with multiple unknown knots? | I once came across a program called Joinpoint. On their website they say it fits a joinpoint model where "several different lines are connected together at the 'joinpoints'". And further: "The user su | How to do piecewise linear regression with multiple unknown knots?
I once came across a program called Joinpoint. On their website they say it fits a joinpoint model where "several different lines are connected together at the 'joinpoints'". And further: "The user supplies the minimum and maximum number of joinpoints. The program starts with the minimum number of joinpoint (e.g. 0 joinpoints, which is a straight line) and tests whether more joinpoints are statistically significant and must be added to the model (up to that maximum number)."
The NCI uses it for trend modelling of cancer rates, maybe it fits your needs as well. | How to do piecewise linear regression with multiple unknown knots?
I once came across a program called Joinpoint. On their website they say it fits a joinpoint model where "several different lines are connected together at the 'joinpoints'". And further: "The user su |
17,411 | How to do piecewise linear regression with multiple unknown knots? | In order to fit to data a piecewise function :
where $a_1 , a_2 , p_1 , q_1, p_2 , q_2 , p_3 , q_3$ are unknown parameters to be approximately computed, there is a very simple method (not iterative, no initial guess, easy to code in any math computer language). The theory given page 29 in paper : https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf and from page 30 :
For example, with the exact data provided by Mats Granvik the result is :
Without scattered data, this example is not very signifiant. Other examples with scattered data are shown in the referenced paper. | How to do piecewise linear regression with multiple unknown knots? | In order to fit to data a piecewise function :
where $a_1 , a_2 , p_1 , q_1, p_2 , q_2 , p_3 , q_3$ are unknown parameters to be approximately computed, there is a very simple method (not iterative, | How to do piecewise linear regression with multiple unknown knots?
In order to fit to data a piecewise function :
where $a_1 , a_2 , p_1 , q_1, p_2 , q_2 , p_3 , q_3$ are unknown parameters to be approximately computed, there is a very simple method (not iterative, no initial guess, easy to code in any math computer language). The theory given page 29 in paper : https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf and from page 30 :
For example, with the exact data provided by Mats Granvik the result is :
Without scattered data, this example is not very signifiant. Other examples with scattered data are shown in the referenced paper. | How to do piecewise linear regression with multiple unknown knots?
In order to fit to data a piecewise function :
where $a_1 , a_2 , p_1 , q_1, p_2 , q_2 , p_3 , q_3$ are unknown parameters to be approximately computed, there is a very simple method (not iterative, |
17,412 | How to do piecewise linear regression with multiple unknown knots? | You can use the mcp package if you know the number of change points to infer. It gives you great modeling flexibility and a lot of information about the change points and regression parameters, but at the cost of speed.
The mcp website contains many applied examples, e.g.,
library(mcp)
# Define the model
model = list(
response ~ 1, # plateau (int_1)
~ 0 + time, # joined slope (time_2) at cp_1
~ 1 + time # disjoined slope (int_3, time_3) at cp_2
)
# Fit it. The `ex_demo` dataset is included in mcp
fit = mcp(model, data = ex_demo)
Then you can visualize:
plot(fit)
Or summarise:
summary(fit)
Family: gaussian(link = 'identity')
Iterations: 9000 from 3 chains.
Segments:
1: response ~ 1
2: response ~ 1 ~ 0 + time
3: response ~ 1 ~ 1 + time
Population-level parameters:
name match sim mean lower upper Rhat n.eff
cp_1 OK 30.0 30.27 23.19 38.760 1 384
cp_2 OK 70.0 69.78 69.27 70.238 1 5792
int_1 OK 10.0 10.26 8.82 11.768 1 1480
int_3 OK 0.0 0.44 -2.49 3.428 1 810
sigma_1 OK 4.0 4.01 3.43 4.591 1 3852
time_2 OK 0.5 0.53 0.40 0.662 1 437
time_3 OK -0.2 -0.22 -0.38 -0.035 1 834
Disclaimer: I am the developer of mcp. | How to do piecewise linear regression with multiple unknown knots? | You can use the mcp package if you know the number of change points to infer. It gives you great modeling flexibility and a lot of information about the change points and regression parameters, but at | How to do piecewise linear regression with multiple unknown knots?
You can use the mcp package if you know the number of change points to infer. It gives you great modeling flexibility and a lot of information about the change points and regression parameters, but at the cost of speed.
The mcp website contains many applied examples, e.g.,
library(mcp)
# Define the model
model = list(
response ~ 1, # plateau (int_1)
~ 0 + time, # joined slope (time_2) at cp_1
~ 1 + time # disjoined slope (int_3, time_3) at cp_2
)
# Fit it. The `ex_demo` dataset is included in mcp
fit = mcp(model, data = ex_demo)
Then you can visualize:
plot(fit)
Or summarise:
summary(fit)
Family: gaussian(link = 'identity')
Iterations: 9000 from 3 chains.
Segments:
1: response ~ 1
2: response ~ 1 ~ 0 + time
3: response ~ 1 ~ 1 + time
Population-level parameters:
name match sim mean lower upper Rhat n.eff
cp_1 OK 30.0 30.27 23.19 38.760 1 384
cp_2 OK 70.0 69.78 69.27 70.238 1 5792
int_1 OK 10.0 10.26 8.82 11.768 1 1480
int_3 OK 0.0 0.44 -2.49 3.428 1 810
sigma_1 OK 4.0 4.01 3.43 4.591 1 3852
time_2 OK 0.5 0.53 0.40 0.662 1 437
time_3 OK -0.2 -0.22 -0.38 -0.035 1 834
Disclaimer: I am the developer of mcp. | How to do piecewise linear regression with multiple unknown knots?
You can use the mcp package if you know the number of change points to infer. It gives you great modeling flexibility and a lot of information about the change points and regression parameters, but at |
17,413 | Why do we use masking for padding in the Transformer's encoder? | I hadn't realized this question was unanswered. If I were to attempt to answer my own question, we apply masks to the source data because after the data passes through the Encoder sublayer, there are values for the padding sequences. We don't need nor want the model to attend to these padding sequences, and so we mask them out.
It's slightly different from masking in the decoder in the sense that masking in the decoder takes an additional step of having a "no peeking" mechanism so that our model can't look at future tokens. | Why do we use masking for padding in the Transformer's encoder? | I hadn't realized this question was unanswered. If I were to attempt to answer my own question, we apply masks to the source data because after the data passes through the Encoder sublayer, there are | Why do we use masking for padding in the Transformer's encoder?
I hadn't realized this question was unanswered. If I were to attempt to answer my own question, we apply masks to the source data because after the data passes through the Encoder sublayer, there are values for the padding sequences. We don't need nor want the model to attend to these padding sequences, and so we mask them out.
It's slightly different from masking in the decoder in the sense that masking in the decoder takes an additional step of having a "no peeking" mechanism so that our model can't look at future tokens. | Why do we use masking for padding in the Transformer's encoder?
I hadn't realized this question was unanswered. If I were to attempt to answer my own question, we apply masks to the source data because after the data passes through the Encoder sublayer, there are |
17,414 | Why do we use masking for padding in the Transformer's encoder? | The mask is simply to ensure that the encoder doesn't pay any
attention to padding tokens. Here is the formula for the masked scaled
dot product attention:
$$
\mathrm{Attention}(Q, K, V, M) = \mathrm{softmax}\left(\frac{QK^T}{\sqrt{d_k}}M\right)V
$$
Softmax outputs a probability distribution. By setting the mask vector
$M$ to a value close to negative infinity where we have padding tokens
and 1 otherwise, we ensure that no attention is paid to those tokens. | Why do we use masking for padding in the Transformer's encoder? | The mask is simply to ensure that the encoder doesn't pay any
attention to padding tokens. Here is the formula for the masked scaled
dot product attention:
$$
\mathrm{Attention}(Q, K, V, M) = \mat | Why do we use masking for padding in the Transformer's encoder?
The mask is simply to ensure that the encoder doesn't pay any
attention to padding tokens. Here is the formula for the masked scaled
dot product attention:
$$
\mathrm{Attention}(Q, K, V, M) = \mathrm{softmax}\left(\frac{QK^T}{\sqrt{d_k}}M\right)V
$$
Softmax outputs a probability distribution. By setting the mask vector
$M$ to a value close to negative infinity where we have padding tokens
and 1 otherwise, we ensure that no attention is paid to those tokens. | Why do we use masking for padding in the Transformer's encoder?
The mask is simply to ensure that the encoder doesn't pay any
attention to padding tokens. Here is the formula for the masked scaled
dot product attention:
$$
\mathrm{Attention}(Q, K, V, M) = \mat |
17,415 | Why do we use masking for padding in the Transformer's encoder? | Answer is: we don't want softmax in attention to be affected by padded parts of sequences.
Sequences have different lengths:
if sequence is too long, we trim it down
if sequence is too shot, we pad remaining part with either tokens or values like 0
But these values in embeddings, further down the road, will affect attention's output, because of softmax:
For example, if we have vector = [2, 0.5, 0.8, 1, 0, 0, 0, 0] (last 4 values are padded part), softmax output will be [0.41, 0.09, 0.12, 0.15, 0.06, 0.06, 0.06, 0.06], yet, we know that last four elements have no real value and shouldn't influence output.
Thus, we create mask and apply it before softmax, setting padded values to -inf or something like -1e9. For example, previous vector after replacement will look like this: [2, 0.5, 0.8, 1, -1e9, -1e9, -1e9, -1e9] and here's softmax output: [0.53, 0.12, 0.16, 0.19, 0, 0, 0, 0] | Why do we use masking for padding in the Transformer's encoder? | Answer is: we don't want softmax in attention to be affected by padded parts of sequences.
Sequences have different lengths:
if sequence is too long, we trim it down
if sequence is too shot, we pad r | Why do we use masking for padding in the Transformer's encoder?
Answer is: we don't want softmax in attention to be affected by padded parts of sequences.
Sequences have different lengths:
if sequence is too long, we trim it down
if sequence is too shot, we pad remaining part with either tokens or values like 0
But these values in embeddings, further down the road, will affect attention's output, because of softmax:
For example, if we have vector = [2, 0.5, 0.8, 1, 0, 0, 0, 0] (last 4 values are padded part), softmax output will be [0.41, 0.09, 0.12, 0.15, 0.06, 0.06, 0.06, 0.06], yet, we know that last four elements have no real value and shouldn't influence output.
Thus, we create mask and apply it before softmax, setting padded values to -inf or something like -1e9. For example, previous vector after replacement will look like this: [2, 0.5, 0.8, 1, -1e9, -1e9, -1e9, -1e9] and here's softmax output: [0.53, 0.12, 0.16, 0.19, 0, 0, 0, 0] | Why do we use masking for padding in the Transformer's encoder?
Answer is: we don't want softmax in attention to be affected by padded parts of sequences.
Sequences have different lengths:
if sequence is too long, we trim it down
if sequence is too shot, we pad r |
17,416 | Why do we use masking for padding in the Transformer's encoder? | I think it may be due to we don't want to compute the loss of padding and the weight of the padding position should be $0.$ | Why do we use masking for padding in the Transformer's encoder? | I think it may be due to we don't want to compute the loss of padding and the weight of the padding position should be $0.$ | Why do we use masking for padding in the Transformer's encoder?
I think it may be due to we don't want to compute the loss of padding and the weight of the padding position should be $0.$ | Why do we use masking for padding in the Transformer's encoder?
I think it may be due to we don't want to compute the loss of padding and the weight of the padding position should be $0.$ |
17,417 | Why do we use masking for padding in the Transformer's encoder? | For an encoder we only padded masks, to a decoder we apply both causal mask and padded mask, covering only the encoder part the padded masks help the model to ignore those dummy padded values. so the model focuses only on the useful part of the sequence. | Why do we use masking for padding in the Transformer's encoder? | For an encoder we only padded masks, to a decoder we apply both causal mask and padded mask, covering only the encoder part the padded masks help the model to ignore those dummy padded values. so the | Why do we use masking for padding in the Transformer's encoder?
For an encoder we only padded masks, to a decoder we apply both causal mask and padded mask, covering only the encoder part the padded masks help the model to ignore those dummy padded values. so the model focuses only on the useful part of the sequence. | Why do we use masking for padding in the Transformer's encoder?
For an encoder we only padded masks, to a decoder we apply both causal mask and padded mask, covering only the encoder part the padded masks help the model to ignore those dummy padded values. so the |
17,418 | Why do we use masking for padding in the Transformer's encoder? | Just an example why people want to apply masks to encoders.
There're unsupervised language models pre-trained with an unidirectional mask, for example GPT. If we want to leverage this pre-trained language model to build a encoder-decoder based machine translation model, we might want to apply the unidirectional mask in the same fashion it's pre-trained with. | Why do we use masking for padding in the Transformer's encoder? | Just an example why people want to apply masks to encoders.
There're unsupervised language models pre-trained with an unidirectional mask, for example GPT. If we want to leverage this pre-trained lang | Why do we use masking for padding in the Transformer's encoder?
Just an example why people want to apply masks to encoders.
There're unsupervised language models pre-trained with an unidirectional mask, for example GPT. If we want to leverage this pre-trained language model to build a encoder-decoder based machine translation model, we might want to apply the unidirectional mask in the same fashion it's pre-trained with. | Why do we use masking for padding in the Transformer's encoder?
Just an example why people want to apply masks to encoders.
There're unsupervised language models pre-trained with an unidirectional mask, for example GPT. If we want to leverage this pre-trained lang |
17,419 | Causal effect by back-door and front-door adjustments | The action $do(x)$ corresponds to an intervention on variable $X$ that sets it to $x$. When we intervene on $X$, this means the parents of $X$ do not affect its value anymore, which corresponds to removing the arrows pointing to $X$.So let's represent this intervention on a new DAG.
Let's call the original observational distribution $P$ and the post-intervention distribution $P^*$. Our goal is to express $P^*$ in terms of $P$. Notice that in $P^*$ we have that $U \perp X$. Also, the pre interventional and post interventional probabilities share these two invariances: $P^*(U) = P(U)$ and $P^*(Y|X, U) = P(Y|X, U)$ since we did not touch any arrow entering those variables in our intervention. So:
$$
\begin{aligned}
P(Y|do(X)) &:= P^*(Y|X) \\
&=\sum_{U}P^*(Y|X, U)P^*(U|X)\\
&=\sum_{U}P^*(Y|X, U)P^*(U)\\
&=\sum_{U}P(Y|X, U)P(U)
\end{aligned}
$$
The derivation of the front door is a bit more elaborate. First notice that there's no confounding between $X$ and $Z$, hence,
$$P(Z|do(X)) = P(Z|X)$$
Also, using the same logic for deriving $P(Y|do(X))$ we see that controlling for $X$ is enough for deriving the effect of $Z$ on $Y$, that is
$$P(Y|do(Z)) = \sum_{X'}P(Y|X', Z) P(X')$$
Where I'm using the prime for notation convenience for the next expression. So these two expressions are already in terms of the pre-intervention distribution, and we simply used the previous backdoor rationale to derive them.
The last piece we need is to infer the effect of $X$ on $Y$ combining the effect of $Z$ on $Y$ and $X$ on $Z$. To do that, notice in our graph $P(Y|Z, do(X)) = P(Y|do(Z), do(X)) = P(Y|do(Z))$, since the effect of $X$ on $Y$ is completely mediated by $Z$ and the backdoor path from $Z$ to $Y$ is blocked when intervening on $X$. Hence:
$$
\begin{aligned}
P(Y|do(X)) &= \sum_{Z} P(Y|Z, do(X))P(Z|do(X))\\
&= \sum_{Z} P(Y|do(Z))P(Z|do(X))\\
&= \sum_{Z} \sum_{X'}P(Y|X', Z) P(X')P(Z|X)\\
&= \sum_{Z}P(Z|X) \sum_{X'}P(Y|X', Z) P(X')
\end{aligned}
$$
Where $\sum_{Z} P(Y|do(Z))P(Z|do(X))$ can be understood in the following way: when I intervene on $Z$, then the distribution of $Y$ changes to $P(Y|do(Z))$; but I'm actually intervening on $X$ so I want to know how often would $Z$ take a specific value when I change $X$, which is $P(Z|do(X))$.
Hence, the two adjustments give you the same post-interventional distribution on this graph, as we have showed.
Re-reading your question it occurred to me you might be interested in directly showing that the right hand side of the two equations are equal in the pre-interventional distribution (which they must be, given our previous derivation). That's not hard to show directly too. It suffices to show that in your DAG:
$$
\sum_{X'}P(Y|Z, X') P(X') = \sum_{U}P(Y|Z, U) P(U)
$$
Notice the DAG implies $Y \perp X|U, Z$ and $U \perp Z|X$ then:
$$
\begin{aligned}
\sum_{X'}P(Y|Z, X') P(X') &= \sum_{X'}\left(\sum_{U}P(Y|Z, X', U)P(U|Z, X') \right)P(X') \\
&= \sum_{X'}\left(\sum_{U}P(Y|Z, U)P(U| X') \right)P(X') \\
&= \sum_{U}P(Y|Z, U) \sum_{X'}P(U| X')P(X') \\
&= \sum_{U}P(Y|Z, U) P(U) \\
\end{aligned}
$$
Hence:
$$
\begin{aligned}
\sum_{Z}P(Z|X) \sum_{X'}P(Y|X', Z) P(X') &= \sum_{Z}P(Z|X)\sum_{U}P(Y|Z, U) P(U)\\
&= \sum_{U}P(U)\sum_{Z}P(Y|Z, U)P(Z|X) \\
&= \sum_{U}P(U)\sum_{Z}P(Y|Z, X, U)P(Z|X, U) \\
&= \sum_{U}P(Y| X, U) P(U)\\
\end{aligned}
$$ | Causal effect by back-door and front-door adjustments | The action $do(x)$ corresponds to an intervention on variable $X$ that sets it to $x$. When we intervene on $X$, this means the parents of $X$ do not affect its value anymore, which corresponds to re | Causal effect by back-door and front-door adjustments
The action $do(x)$ corresponds to an intervention on variable $X$ that sets it to $x$. When we intervene on $X$, this means the parents of $X$ do not affect its value anymore, which corresponds to removing the arrows pointing to $X$.So let's represent this intervention on a new DAG.
Let's call the original observational distribution $P$ and the post-intervention distribution $P^*$. Our goal is to express $P^*$ in terms of $P$. Notice that in $P^*$ we have that $U \perp X$. Also, the pre interventional and post interventional probabilities share these two invariances: $P^*(U) = P(U)$ and $P^*(Y|X, U) = P(Y|X, U)$ since we did not touch any arrow entering those variables in our intervention. So:
$$
\begin{aligned}
P(Y|do(X)) &:= P^*(Y|X) \\
&=\sum_{U}P^*(Y|X, U)P^*(U|X)\\
&=\sum_{U}P^*(Y|X, U)P^*(U)\\
&=\sum_{U}P(Y|X, U)P(U)
\end{aligned}
$$
The derivation of the front door is a bit more elaborate. First notice that there's no confounding between $X$ and $Z$, hence,
$$P(Z|do(X)) = P(Z|X)$$
Also, using the same logic for deriving $P(Y|do(X))$ we see that controlling for $X$ is enough for deriving the effect of $Z$ on $Y$, that is
$$P(Y|do(Z)) = \sum_{X'}P(Y|X', Z) P(X')$$
Where I'm using the prime for notation convenience for the next expression. So these two expressions are already in terms of the pre-intervention distribution, and we simply used the previous backdoor rationale to derive them.
The last piece we need is to infer the effect of $X$ on $Y$ combining the effect of $Z$ on $Y$ and $X$ on $Z$. To do that, notice in our graph $P(Y|Z, do(X)) = P(Y|do(Z), do(X)) = P(Y|do(Z))$, since the effect of $X$ on $Y$ is completely mediated by $Z$ and the backdoor path from $Z$ to $Y$ is blocked when intervening on $X$. Hence:
$$
\begin{aligned}
P(Y|do(X)) &= \sum_{Z} P(Y|Z, do(X))P(Z|do(X))\\
&= \sum_{Z} P(Y|do(Z))P(Z|do(X))\\
&= \sum_{Z} \sum_{X'}P(Y|X', Z) P(X')P(Z|X)\\
&= \sum_{Z}P(Z|X) \sum_{X'}P(Y|X', Z) P(X')
\end{aligned}
$$
Where $\sum_{Z} P(Y|do(Z))P(Z|do(X))$ can be understood in the following way: when I intervene on $Z$, then the distribution of $Y$ changes to $P(Y|do(Z))$; but I'm actually intervening on $X$ so I want to know how often would $Z$ take a specific value when I change $X$, which is $P(Z|do(X))$.
Hence, the two adjustments give you the same post-interventional distribution on this graph, as we have showed.
Re-reading your question it occurred to me you might be interested in directly showing that the right hand side of the two equations are equal in the pre-interventional distribution (which they must be, given our previous derivation). That's not hard to show directly too. It suffices to show that in your DAG:
$$
\sum_{X'}P(Y|Z, X') P(X') = \sum_{U}P(Y|Z, U) P(U)
$$
Notice the DAG implies $Y \perp X|U, Z$ and $U \perp Z|X$ then:
$$
\begin{aligned}
\sum_{X'}P(Y|Z, X') P(X') &= \sum_{X'}\left(\sum_{U}P(Y|Z, X', U)P(U|Z, X') \right)P(X') \\
&= \sum_{X'}\left(\sum_{U}P(Y|Z, U)P(U| X') \right)P(X') \\
&= \sum_{U}P(Y|Z, U) \sum_{X'}P(U| X')P(X') \\
&= \sum_{U}P(Y|Z, U) P(U) \\
\end{aligned}
$$
Hence:
$$
\begin{aligned}
\sum_{Z}P(Z|X) \sum_{X'}P(Y|X', Z) P(X') &= \sum_{Z}P(Z|X)\sum_{U}P(Y|Z, U) P(U)\\
&= \sum_{U}P(U)\sum_{Z}P(Y|Z, U)P(Z|X) \\
&= \sum_{U}P(U)\sum_{Z}P(Y|Z, X, U)P(Z|X, U) \\
&= \sum_{U}P(Y| X, U) P(U)\\
\end{aligned}
$$ | Causal effect by back-door and front-door adjustments
The action $do(x)$ corresponds to an intervention on variable $X$ that sets it to $x$. When we intervene on $X$, this means the parents of $X$ do not affect its value anymore, which corresponds to re |
17,420 | A simple & clear explanation of the Gini impurity? | Imagine an experiment with $k$ possible output categories. Category $j$ has a probability of occurrence $p(j|t)$ (where $j=1,..k$)
Reproduce the experiment two times and make these observations:
the probability of obtaining two identical outputs of category $j$ is $$ p^2(j|t) $$
the probability of obtaining two identical outputs, independently of their category, is: $$\sum\limits_{j=1}^k p^2(j|t)$$
the probability of obtaining two different outputs is thus: $$1-\sum\limits_{j=1}^k p^2(j|t)$$
That's it: the Gini impurity is simply the probability of obtaining two different outputs, which is an "impurity measure".
Remark: another expression of the Gini index is:
$$
\sum\limits_{j=1}^k p_j(1-p_j)
$$
This is the same quantity:
$$
\sum\limits_{j=1}^k p_j(1-p_j) = \left(\sum\limits_{j=1}^k p_j \right) -\left( \sum\limits_{j=1}^k p^2_j \right) = 1 - \sum\limits_{j=1}^k p^2_j
$$ | A simple & clear explanation of the Gini impurity? | Imagine an experiment with $k$ possible output categories. Category $j$ has a probability of occurrence $p(j|t)$ (where $j=1,..k$)
Reproduce the experiment two times and make these observations:
the | A simple & clear explanation of the Gini impurity?
Imagine an experiment with $k$ possible output categories. Category $j$ has a probability of occurrence $p(j|t)$ (where $j=1,..k$)
Reproduce the experiment two times and make these observations:
the probability of obtaining two identical outputs of category $j$ is $$ p^2(j|t) $$
the probability of obtaining two identical outputs, independently of their category, is: $$\sum\limits_{j=1}^k p^2(j|t)$$
the probability of obtaining two different outputs is thus: $$1-\sum\limits_{j=1}^k p^2(j|t)$$
That's it: the Gini impurity is simply the probability of obtaining two different outputs, which is an "impurity measure".
Remark: another expression of the Gini index is:
$$
\sum\limits_{j=1}^k p_j(1-p_j)
$$
This is the same quantity:
$$
\sum\limits_{j=1}^k p_j(1-p_j) = \left(\sum\limits_{j=1}^k p_j \right) -\left( \sum\limits_{j=1}^k p^2_j \right) = 1 - \sum\limits_{j=1}^k p^2_j
$$ | A simple & clear explanation of the Gini impurity?
Imagine an experiment with $k$ possible output categories. Category $j$ has a probability of occurrence $p(j|t)$ (where $j=1,..k$)
Reproduce the experiment two times and make these observations:
the |
17,421 | A simple & clear explanation of the Gini impurity? | Gini impurity = logical entropy = Gini-Simpson biodiversity index = quadratic entropy with logical distance function (1-Kroneckerdelta), etc.
See: Ellerman, David. 2018. “Logical Entropy: Introduction to Classical and Quantum Logical Information Theory.” Entropy 20 (9): Article ID 679. https://doi.org/10.3390/e20090679, and the references contained therein. | A simple & clear explanation of the Gini impurity? | Gini impurity = logical entropy = Gini-Simpson biodiversity index = quadratic entropy with logical distance function (1-Kroneckerdelta), etc.
See: Ellerman, David. 2018. “Logical Entropy: Introduction | A simple & clear explanation of the Gini impurity?
Gini impurity = logical entropy = Gini-Simpson biodiversity index = quadratic entropy with logical distance function (1-Kroneckerdelta), etc.
See: Ellerman, David. 2018. “Logical Entropy: Introduction to Classical and Quantum Logical Information Theory.” Entropy 20 (9): Article ID 679. https://doi.org/10.3390/e20090679, and the references contained therein. | A simple & clear explanation of the Gini impurity?
Gini impurity = logical entropy = Gini-Simpson biodiversity index = quadratic entropy with logical distance function (1-Kroneckerdelta), etc.
See: Ellerman, David. 2018. “Logical Entropy: Introduction |
17,422 | Common Continuous Distributions with [0,1] support | Wikipedia has a list of distributions supported on an interval
Leaving aside mixtures and 0-inflated and 0-1 inflated cases (though you should definitely be aware of all of those if you model data on the unit interval), which ones are common would be hard to establish (it will vary across application areas for example), but the beta family, and the triangular, and the truncated normal would probably be the main candidates as they seem to be used in a variety of situations.
Each of them can be defined on (0,1) and can be skewed either direction.
One example of each is shown here:
That they're often used doesn't imply they'll be suitable for whatever situation you're in, though. Model choice should be based on a number of considerations, but where possible, theoretical understanding and practical subject area knowledge are both important.
I always struggle to find the best distribution to explain this data.
You should get away from worrying about "best", and focus on "sufficient/adequate for the present purpose". No simple distribution such as the ones I mentioned will really be a perfect description of real data ("all models are wrong..."), and what might be fine for one purpose ("... some are useful") may be inadequate for some other purpose.
Edit to address information in comments:
If you have exact zeros (or exact ones, or both), then
you will need to model the probability of those 0's and use a mixture distribution (a 0-inflated distribution if you can have exact 0's) --
shouldn't use a continuous distribution.
It's not really all that hard to deal with simple mixtures. You'll no longer have a density but the cdf is not much more effort to write down or evaluate than it would be in the continuous case; similarly quantiles are not much more effort either; means and variances are almost as readily calculated as before; and they're easy to simulate from.
Taking an existing continuous distribution on the unit interval and adding a proportion of zeros (and/or ones) is on the whole a pretty convenient way to model proportions that are mostly continuous but can be 0 or 1. | Common Continuous Distributions with [0,1] support | Wikipedia has a list of distributions supported on an interval
Leaving aside mixtures and 0-inflated and 0-1 inflated cases (though you should definitely be aware of all of those if you model data on | Common Continuous Distributions with [0,1] support
Wikipedia has a list of distributions supported on an interval
Leaving aside mixtures and 0-inflated and 0-1 inflated cases (though you should definitely be aware of all of those if you model data on the unit interval), which ones are common would be hard to establish (it will vary across application areas for example), but the beta family, and the triangular, and the truncated normal would probably be the main candidates as they seem to be used in a variety of situations.
Each of them can be defined on (0,1) and can be skewed either direction.
One example of each is shown here:
That they're often used doesn't imply they'll be suitable for whatever situation you're in, though. Model choice should be based on a number of considerations, but where possible, theoretical understanding and practical subject area knowledge are both important.
I always struggle to find the best distribution to explain this data.
You should get away from worrying about "best", and focus on "sufficient/adequate for the present purpose". No simple distribution such as the ones I mentioned will really be a perfect description of real data ("all models are wrong..."), and what might be fine for one purpose ("... some are useful") may be inadequate for some other purpose.
Edit to address information in comments:
If you have exact zeros (or exact ones, or both), then
you will need to model the probability of those 0's and use a mixture distribution (a 0-inflated distribution if you can have exact 0's) --
shouldn't use a continuous distribution.
It's not really all that hard to deal with simple mixtures. You'll no longer have a density but the cdf is not much more effort to write down or evaluate than it would be in the continuous case; similarly quantiles are not much more effort either; means and variances are almost as readily calculated as before; and they're easy to simulate from.
Taking an existing continuous distribution on the unit interval and adding a proportion of zeros (and/or ones) is on the whole a pretty convenient way to model proportions that are mostly continuous but can be 0 or 1. | Common Continuous Distributions with [0,1] support
Wikipedia has a list of distributions supported on an interval
Leaving aside mixtures and 0-inflated and 0-1 inflated cases (though you should definitely be aware of all of those if you model data on |
17,423 | Common Continuous Distributions with [0,1] support | Adding to Glen_b's answer, notice that if you are dealing with a continuous random variable, then in theory it shouldn't really matter if the distribution supports $[0, 1]$, or $(0, 1)$ bounds as $\Pr(X=0) = \Pr(X=1) = 0$ (see $P[X=x]=0$ when $X$ is continuous variable). In real life you meet exact zeros and ones due to measurement precision issues and the common workaround is to apply the simple "squeezing" transformations to move them away from the bounds (see Dealing with 0,1 values in a beta regression and
Beta regression of proportion data including 1 and 0). See also then Why exactly can't beta regression deal with 0s and 1s in the response variable? thread for related discussion.
So inclusive bounds should not concern you that much when considering common bounded distributions like beta, Kumarshwamy, triangular distribution etc.
If, as you are saying, your data has exact zeros for other reasons then measurement precision issues, then you are dealing with mixed-type data and you should consider zero-inflated models, i.e. using mixture distribution in form
$$
g(x) = \begin{cases}
\pi + (1-\pi) f(x) & x = 0 \\
(1-\pi) f(x) & x > 0
\end{cases}
$$
where $f$ is non-zero-inflated distribution and $\pi$ is the mixing parameter controlling for the probability of excess zeros in your data, what follows is that if $f(0)=0$, then $g(0) = \pi$ for distributions $f$ with non-inclusive bounds. You can easily extend this line of reasoning to zero-and-one inflated model etc. | Common Continuous Distributions with [0,1] support | Adding to Glen_b's answer, notice that if you are dealing with a continuous random variable, then in theory it shouldn't really matter if the distribution supports $[0, 1]$, or $(0, 1)$ bounds as $\Pr | Common Continuous Distributions with [0,1] support
Adding to Glen_b's answer, notice that if you are dealing with a continuous random variable, then in theory it shouldn't really matter if the distribution supports $[0, 1]$, or $(0, 1)$ bounds as $\Pr(X=0) = \Pr(X=1) = 0$ (see $P[X=x]=0$ when $X$ is continuous variable). In real life you meet exact zeros and ones due to measurement precision issues and the common workaround is to apply the simple "squeezing" transformations to move them away from the bounds (see Dealing with 0,1 values in a beta regression and
Beta regression of proportion data including 1 and 0). See also then Why exactly can't beta regression deal with 0s and 1s in the response variable? thread for related discussion.
So inclusive bounds should not concern you that much when considering common bounded distributions like beta, Kumarshwamy, triangular distribution etc.
If, as you are saying, your data has exact zeros for other reasons then measurement precision issues, then you are dealing with mixed-type data and you should consider zero-inflated models, i.e. using mixture distribution in form
$$
g(x) = \begin{cases}
\pi + (1-\pi) f(x) & x = 0 \\
(1-\pi) f(x) & x > 0
\end{cases}
$$
where $f$ is non-zero-inflated distribution and $\pi$ is the mixing parameter controlling for the probability of excess zeros in your data, what follows is that if $f(0)=0$, then $g(0) = \pi$ for distributions $f$ with non-inclusive bounds. You can easily extend this line of reasoning to zero-and-one inflated model etc. | Common Continuous Distributions with [0,1] support
Adding to Glen_b's answer, notice that if you are dealing with a continuous random variable, then in theory it shouldn't really matter if the distribution supports $[0, 1]$, or $(0, 1)$ bounds as $\Pr |
17,424 | Common Continuous Distributions with [0,1] support | This is a book dedicated to alternatives to the beta distribution for modeling distributions on $[0,1]$:
Then there are other posts on this site with answers:
Distribution that has a range from 0 to 1 and with peak between them?
Scaling normal $X$ into (0, 1) range whist maintaining distribution shape | Common Continuous Distributions with [0,1] support | This is a book dedicated to alternatives to the beta distribution for modeling distributions on $[0,1]$:
Then there are other posts on this site with answers:
Distribution that has a range from 0 to | Common Continuous Distributions with [0,1] support
This is a book dedicated to alternatives to the beta distribution for modeling distributions on $[0,1]$:
Then there are other posts on this site with answers:
Distribution that has a range from 0 to 1 and with peak between them?
Scaling normal $X$ into (0, 1) range whist maintaining distribution shape | Common Continuous Distributions with [0,1] support
This is a book dedicated to alternatives to the beta distribution for modeling distributions on $[0,1]$:
Then there are other posts on this site with answers:
Distribution that has a range from 0 to |
17,425 | Principal Component Analysis Eliminate Noise In The Data | Principal Component Analysis (PCA) is used to a) denoise and to b) reduce dimensionality.
It does not eliminate noise, but it can reduce noise.
Basically an orthogonal linear transformation is used to find a projection of all data into k dimensions, whereas these k dimensions are those of the highest variance.
The eigenvectors of the covariance matrix (of the dataset) are the target dimensions and they can be ranked according to their eigenvalues. A high eigenvalue signifies high variance explained by the associated eigenvector dimension.
Lets take a look at the usps dataset, obtained by scanning handwritten digits from envelopes by the U.S. Postal Service.
First, we compute the eigenvectors and eigenvalues of the covariance matrix and plot all eigenvalues descending. We can see that there a few eigenvalues which could be named principal components, since their eigenvalues are much higher than the rest.
Each eigenvector is a linear combination of original dimensions. Therefore, the eigenvector (in this case) is an image itself, which can be plotted.
For b) dimensionality reduction, we could now use the top five eigenvectors and project all data (originally a 16*16 pixel image) into a 5 dimensional space with least possible loss of variance.
(Note here: In some cases, non-linear dimensionality reduction (such as LLE) might be better than PCA, see wikipedia for examples)
Finally we can use PCA for denoising. Therefore we can add extra noise to the original dataset in three levels (low, high, outlier) to be able to compare the performance. For this case I used gaussian noise with mean of zero and variance as a multiple of the original variance (Factor 1 (low), Factor 2 (high), Factor 20 (outlier) )
A possible result looks like this. Yet in each case, the parameter k must be tuned to find a good result.
Finally another perspective is to compare the eigenvalues of the highly noised data with the original data (compare with the first picture of this answer). You can see that the noise affects all eigenvalues, thus using only the top 25 eigenvalues for denoising, the influence of noise is reduced. | Principal Component Analysis Eliminate Noise In The Data | Principal Component Analysis (PCA) is used to a) denoise and to b) reduce dimensionality.
It does not eliminate noise, but it can reduce noise.
Basically an orthogonal linear transformation is used t | Principal Component Analysis Eliminate Noise In The Data
Principal Component Analysis (PCA) is used to a) denoise and to b) reduce dimensionality.
It does not eliminate noise, but it can reduce noise.
Basically an orthogonal linear transformation is used to find a projection of all data into k dimensions, whereas these k dimensions are those of the highest variance.
The eigenvectors of the covariance matrix (of the dataset) are the target dimensions and they can be ranked according to their eigenvalues. A high eigenvalue signifies high variance explained by the associated eigenvector dimension.
Lets take a look at the usps dataset, obtained by scanning handwritten digits from envelopes by the U.S. Postal Service.
First, we compute the eigenvectors and eigenvalues of the covariance matrix and plot all eigenvalues descending. We can see that there a few eigenvalues which could be named principal components, since their eigenvalues are much higher than the rest.
Each eigenvector is a linear combination of original dimensions. Therefore, the eigenvector (in this case) is an image itself, which can be plotted.
For b) dimensionality reduction, we could now use the top five eigenvectors and project all data (originally a 16*16 pixel image) into a 5 dimensional space with least possible loss of variance.
(Note here: In some cases, non-linear dimensionality reduction (such as LLE) might be better than PCA, see wikipedia for examples)
Finally we can use PCA for denoising. Therefore we can add extra noise to the original dataset in three levels (low, high, outlier) to be able to compare the performance. For this case I used gaussian noise with mean of zero and variance as a multiple of the original variance (Factor 1 (low), Factor 2 (high), Factor 20 (outlier) )
A possible result looks like this. Yet in each case, the parameter k must be tuned to find a good result.
Finally another perspective is to compare the eigenvalues of the highly noised data with the original data (compare with the first picture of this answer). You can see that the noise affects all eigenvalues, thus using only the top 25 eigenvalues for denoising, the influence of noise is reduced. | Principal Component Analysis Eliminate Noise In The Data
Principal Component Analysis (PCA) is used to a) denoise and to b) reduce dimensionality.
It does not eliminate noise, but it can reduce noise.
Basically an orthogonal linear transformation is used t |
17,426 | Principal Component Analysis Eliminate Noise In The Data | PCA is not designed for noise removal purpose. It is designed to REDUCE DIMENSIONS. As a large number of features are difficult to handle. PCA just lets you to approximate your data. Think PCA as a tuning knob. You can smoothly decide how much approximation you want by tuning it and which is impossible to achieve if you work directly with original given features. Because you cannot directly decide which feature to keep and which feature to eliminate to approximate your data at a desired level. Because the original features have no order of their priority or usability on which you can decide on which one to keep and which one to eliminate. That's why PCA comes into the place.
The main difference between the original dimensions and principle components is that, if you are working with original dimensions, you can think that the dimensions were already available before any data points were even plotted. So what wrong can happen? The problem is after plotting the data points these points can be positioned randomly and they may not allow us to eliminate some of the original dimensions directly to approximate it. As depending on the positions of the data points in many cases none of the original feature dimensions may be able to capture good variations notably. So the situation will be like, to capture a decent amount of variations of data you may need to keep a large number of original dimensions. Which is not efficient.
So what's the remedy? One of the remedies is using PCA! In PCA we do the opposite. Here the data points are already there. Now we will be placing the new dimensions (principle components) one by one with the target of capturing most of the variations available at that stage which are not still captured by the previous principle component(s) we have already plotted. Hence, the first PC covers the maximum possible variations (variation is measured by variance) possible to be captured by a single PC. The second PC captures the variations of data less than the first PC and those variations were missed out by the first PC. The third PC again does less than the second PC and so on. So, these principle components are already sorted based on how useful they are or how much variance they can capture. Each of the principle components has two properties - eigenvector and eigenvalue. The measure of the captured variations is nothing but the eigenvalue of that PC and the direction of that PC is just the eigenvector of it. As PCs are also axes and so each of them must have a direction.
So in your case, as you have said in the comment that after applying PCA the performance has improved, this is just because when you are eliminating some of the PCs of lower variances i.e, of lower eigenvalues, this action may be helping the model to generalize well. Because PCs of higher eigenvalues are capturing the more generalized features. As you are taking more and more PCs, the specialized features are also being added. If you take all of them the 100% of the data-variations will be restored like the original dimensions. So removing removing some PCs with lower eigenvalues actually acting as some sort of regularization and your model is only learning the more general features and not being confused by very fine detail which are likely not the general properties of that class. This is how overfitting is being prevented upto a certain level.
But again this doesn't assure you that those very fine example-specific details are noise. Noise can be embedded even with other PCs as well. Because PCA doesn't know which is noise and which is information. As it is just a linear transformation. All the PC axes can be represented by some linear combinations of existing original dimensions. So based on the variation levels of different types noises they can be captured by different PCs. So it is not a guaranteed way to remove noise although noise may be reduced if the eliminated PCs are involved in capturing those noise. But with noise you may also lose information as well. | Principal Component Analysis Eliminate Noise In The Data | PCA is not designed for noise removal purpose. It is designed to REDUCE DIMENSIONS. As a large number of features are difficult to handle. PCA just lets you to approximate your data. Think PCA as a tu | Principal Component Analysis Eliminate Noise In The Data
PCA is not designed for noise removal purpose. It is designed to REDUCE DIMENSIONS. As a large number of features are difficult to handle. PCA just lets you to approximate your data. Think PCA as a tuning knob. You can smoothly decide how much approximation you want by tuning it and which is impossible to achieve if you work directly with original given features. Because you cannot directly decide which feature to keep and which feature to eliminate to approximate your data at a desired level. Because the original features have no order of their priority or usability on which you can decide on which one to keep and which one to eliminate. That's why PCA comes into the place.
The main difference between the original dimensions and principle components is that, if you are working with original dimensions, you can think that the dimensions were already available before any data points were even plotted. So what wrong can happen? The problem is after plotting the data points these points can be positioned randomly and they may not allow us to eliminate some of the original dimensions directly to approximate it. As depending on the positions of the data points in many cases none of the original feature dimensions may be able to capture good variations notably. So the situation will be like, to capture a decent amount of variations of data you may need to keep a large number of original dimensions. Which is not efficient.
So what's the remedy? One of the remedies is using PCA! In PCA we do the opposite. Here the data points are already there. Now we will be placing the new dimensions (principle components) one by one with the target of capturing most of the variations available at that stage which are not still captured by the previous principle component(s) we have already plotted. Hence, the first PC covers the maximum possible variations (variation is measured by variance) possible to be captured by a single PC. The second PC captures the variations of data less than the first PC and those variations were missed out by the first PC. The third PC again does less than the second PC and so on. So, these principle components are already sorted based on how useful they are or how much variance they can capture. Each of the principle components has two properties - eigenvector and eigenvalue. The measure of the captured variations is nothing but the eigenvalue of that PC and the direction of that PC is just the eigenvector of it. As PCs are also axes and so each of them must have a direction.
So in your case, as you have said in the comment that after applying PCA the performance has improved, this is just because when you are eliminating some of the PCs of lower variances i.e, of lower eigenvalues, this action may be helping the model to generalize well. Because PCs of higher eigenvalues are capturing the more generalized features. As you are taking more and more PCs, the specialized features are also being added. If you take all of them the 100% of the data-variations will be restored like the original dimensions. So removing removing some PCs with lower eigenvalues actually acting as some sort of regularization and your model is only learning the more general features and not being confused by very fine detail which are likely not the general properties of that class. This is how overfitting is being prevented upto a certain level.
But again this doesn't assure you that those very fine example-specific details are noise. Noise can be embedded even with other PCs as well. Because PCA doesn't know which is noise and which is information. As it is just a linear transformation. All the PC axes can be represented by some linear combinations of existing original dimensions. So based on the variation levels of different types noises they can be captured by different PCs. So it is not a guaranteed way to remove noise although noise may be reduced if the eliminated PCs are involved in capturing those noise. But with noise you may also lose information as well. | Principal Component Analysis Eliminate Noise In The Data
PCA is not designed for noise removal purpose. It is designed to REDUCE DIMENSIONS. As a large number of features are difficult to handle. PCA just lets you to approximate your data. Think PCA as a tu |
17,427 | Beta distribution on flipping a coin | The quotation is a "logical sleight-of-hand" (great expression!), as noted by @whuber in comments to the OP. The only thing we can really say after seeing that the coin has an head and a tail, is that both the events "head" and "tail" are not impossible. Thus we could discard a discrete prior which puts all of the probability mass on "head" or on "tail". But this doesn't lead, by itself, to the uniform prior: the question is much more subtle. Let's first of all summarize a bit of background. We're considering the Beta-Binominal conjugate model for Bayesian inference of the probability $\theta$ of heads of a coin, given $n$ independent and identically distributed (conditionally on $\theta$) coin tosses. From the expression of $p(\theta|x)$ when we observe $x$ heads in $n$ tosses:
$$ p(\theta|x) = Beta(x+\alpha, n-x+\beta)$$
we can say that $\alpha$ and $\beta$ play the roles of a "prior number of heads" and "prior number of tails" (pseudotrials), and $\alpha+\beta$ can be interpreted as an effective sample size. We could also arrive at this interpretation using the well-known expression for the posterior mean as a weighted average of the prior mean $\frac{\alpha}{\alpha+\beta}$ and the sample mean $\frac{x}{n}$.
Looking at $p(\theta|x)$, we can make two considerations:
since we have no prior knowledge about $\theta$ (maximum ignorance),
we intuitively expect the effective sample size $\alpha+\beta$ to be
"small". If it were large, then the prior would be incorporating
quite a lot of knowledge. Another way of seeing this is noting that
if $\alpha$ and $\beta$ are "small" with respect to $x$ and $n-x$,
the posterior probability won't depend a lot on our prior, because
$x+\alpha\approx x$ and $n-x+\beta\approx n-x$. We would expect that
a prior which doesn't incorporate a lot of knowledge must quickly
become irrelevant in light of some data.
Also, since $\mu_{prior}=\frac{\alpha}{\alpha+\beta}$ is the prior
mean, and we have no prior knowledge about the distribution of
$\theta$, we would expect $\mu_{prior}=0.5$. This is an argument of
symmetry - if we don't know any better, we wouldn't expect a
priori that the distribution is skewed towards 0 or towards 1. The
Beta distribution is
$$f(\theta|\alpha,\beta)=\frac{\Gamma(\alpha +
\beta)}{\Gamma(\alpha)
+\Gamma(\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$$
This expression is only symmetric around $\theta=0.5$ if
$\alpha=\beta$.
For these two reasons, whatever prior (belonging to the Beta family - remember, conjugate model!) we choose to use, we intuitively expect that $\alpha=\beta=c$ and $c$ is "small". We can see that all the three commonly used non-informative priors for the Beta-Binomial model share these traits, but other than that, they are quite different. And this is obvious: no prior knowledge, or "maximum ignorance", is not a scientific definition, so what kind of prior expresses "maximum ignorance", i.e., what's a non-informative prior, depends on what you actually mean as "maximum ignorance".
we could choose a prior which says that all values for $\theta$ are
equiprobable, since we don't know any better. Again, a symmetry
argument. This corresponds to $\alpha=\beta=1$:
$$f(\theta|1,1)=\frac{\Gamma(2)}{2\Gamma(1)}\theta^{0}(1-\theta)^{0}=1$$
for $\theta\in[0,1]$, i.e., the uniform prior used by Kruschke. More
formally, by writing out the expression for the differential entropy
of the Beta distribution, you can see that it is maximized when
$\alpha=\beta=1$. Now, entropy is often interpreted as a measure of "the
amount of information" carried by a distribution: higher entropy corresponds to less information. Thus, you could use this
maximum entropy principle to say that, inside the Beta family, the
prior which contains less information (maximum ignorance) is this
uniform prior.
You could choose another point of view, the one used by the OP, and
say that no information corresponds to having seen no heads and no
tail, i.e.,
$$\alpha=\beta=0 \Rightarrow \pi(\theta) \propto
\theta^{-1}(1-\theta)^{-1}$$
The prior we obtain this way is called the Haldane prior. The
function $\theta^{-1}(1-\theta)^{-1}$ has a little problem - the
integral over $I=[0, 1]$ is infinite, i.e., no matter what the
normalizing constant, it cannot be transformed into a proper pdf.
Actually, the Haldane prior is a proper pmf, which puts
probability 0.5 on $\theta=0$, 0.5 on $\theta=1$ and 0
probability on all other values for $\theta$. However, let's not get
carried away - for a continuous parameter $\theta$, priors which
don't correspond to a proper pdf are called improper priors.
Since, as noted before, all that matters for Bayesian inference is
the posterior distribution, improper priors are admissible, as long
as the posterior distribution is proper. In the case of the Haldane
prior, we can prove that the posterior pdf is proper if our sample
contains at least one success and one failure. Thus we can only use
the Haldane prior when we observe at least one head and one tail.
There's another sense in which the Haldane prior can be considered
non-informative: the mean of the posterior distribution is now
$\frac{\alpha + x}{\alpha + \beta + n}=\frac{x}{n}$, i.e., the
sample frequency of heads, which is the frequentist MLE estimate of
$\theta$ for the Binomial model of the coin flip problem. Also, the
credible intervals for $\theta$ correspond to the Wald confidence
intervals. Since frequentist methods don't specify a prior, one
could say that the Haldane prior is noninformative, or corresponds
to zero prior knowledge, because it leads to the "same" inference a
frequentist would make.
Finally, you could use a prior which doesn't depend on the
parametrization of the problem, i.e., the Jeffreys prior, which for
the Beta-Binomial model corresponds to
$$\alpha=\beta=\frac{1}{2} \Rightarrow \pi(\theta) \propto
\theta^{-\frac{1}{2}}(1-\theta)^{-\frac{1}{2}}$$
thus with an effective sample size of 1. The Jeffreys prior has the
advantage that it's invariant under reparametrization of the
parameter space. For example, the uniform prior assigns equal
probability to all values of $\theta$, the probability of the event
"head". However, you could decide to parametrize this model in terms
of log-odds $\lambda=log(\frac{\theta}{1-\theta})$ of event "head",
instead than $\theta$. What's the prior which expresses "maximum
ignorance" in terms of log-odds, i.e., which says that all possible
log-odds for event "head" are equiprobable? It's the Haldane prior,
as shown in this (slightly cryptic) answer. Instead, the
Jeffreys is invariant under all changes of metric. Jeffreys stated
that a prior which doesn't have this property, is in some way
informative because it contains information on the metric you used
to parametrize the problem. His prior doesn't.
To summarize, there's not just one unequivocal choice for a noninformative prior in the Beta-Binomial model. What you choose depends on what you mean as zero prior knowledge, and on the goals of your analysis. | Beta distribution on flipping a coin | The quotation is a "logical sleight-of-hand" (great expression!), as noted by @whuber in comments to the OP. The only thing we can really say after seeing that the coin has an head and a tail, is that | Beta distribution on flipping a coin
The quotation is a "logical sleight-of-hand" (great expression!), as noted by @whuber in comments to the OP. The only thing we can really say after seeing that the coin has an head and a tail, is that both the events "head" and "tail" are not impossible. Thus we could discard a discrete prior which puts all of the probability mass on "head" or on "tail". But this doesn't lead, by itself, to the uniform prior: the question is much more subtle. Let's first of all summarize a bit of background. We're considering the Beta-Binominal conjugate model for Bayesian inference of the probability $\theta$ of heads of a coin, given $n$ independent and identically distributed (conditionally on $\theta$) coin tosses. From the expression of $p(\theta|x)$ when we observe $x$ heads in $n$ tosses:
$$ p(\theta|x) = Beta(x+\alpha, n-x+\beta)$$
we can say that $\alpha$ and $\beta$ play the roles of a "prior number of heads" and "prior number of tails" (pseudotrials), and $\alpha+\beta$ can be interpreted as an effective sample size. We could also arrive at this interpretation using the well-known expression for the posterior mean as a weighted average of the prior mean $\frac{\alpha}{\alpha+\beta}$ and the sample mean $\frac{x}{n}$.
Looking at $p(\theta|x)$, we can make two considerations:
since we have no prior knowledge about $\theta$ (maximum ignorance),
we intuitively expect the effective sample size $\alpha+\beta$ to be
"small". If it were large, then the prior would be incorporating
quite a lot of knowledge. Another way of seeing this is noting that
if $\alpha$ and $\beta$ are "small" with respect to $x$ and $n-x$,
the posterior probability won't depend a lot on our prior, because
$x+\alpha\approx x$ and $n-x+\beta\approx n-x$. We would expect that
a prior which doesn't incorporate a lot of knowledge must quickly
become irrelevant in light of some data.
Also, since $\mu_{prior}=\frac{\alpha}{\alpha+\beta}$ is the prior
mean, and we have no prior knowledge about the distribution of
$\theta$, we would expect $\mu_{prior}=0.5$. This is an argument of
symmetry - if we don't know any better, we wouldn't expect a
priori that the distribution is skewed towards 0 or towards 1. The
Beta distribution is
$$f(\theta|\alpha,\beta)=\frac{\Gamma(\alpha +
\beta)}{\Gamma(\alpha)
+\Gamma(\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$$
This expression is only symmetric around $\theta=0.5$ if
$\alpha=\beta$.
For these two reasons, whatever prior (belonging to the Beta family - remember, conjugate model!) we choose to use, we intuitively expect that $\alpha=\beta=c$ and $c$ is "small". We can see that all the three commonly used non-informative priors for the Beta-Binomial model share these traits, but other than that, they are quite different. And this is obvious: no prior knowledge, or "maximum ignorance", is not a scientific definition, so what kind of prior expresses "maximum ignorance", i.e., what's a non-informative prior, depends on what you actually mean as "maximum ignorance".
we could choose a prior which says that all values for $\theta$ are
equiprobable, since we don't know any better. Again, a symmetry
argument. This corresponds to $\alpha=\beta=1$:
$$f(\theta|1,1)=\frac{\Gamma(2)}{2\Gamma(1)}\theta^{0}(1-\theta)^{0}=1$$
for $\theta\in[0,1]$, i.e., the uniform prior used by Kruschke. More
formally, by writing out the expression for the differential entropy
of the Beta distribution, you can see that it is maximized when
$\alpha=\beta=1$. Now, entropy is often interpreted as a measure of "the
amount of information" carried by a distribution: higher entropy corresponds to less information. Thus, you could use this
maximum entropy principle to say that, inside the Beta family, the
prior which contains less information (maximum ignorance) is this
uniform prior.
You could choose another point of view, the one used by the OP, and
say that no information corresponds to having seen no heads and no
tail, i.e.,
$$\alpha=\beta=0 \Rightarrow \pi(\theta) \propto
\theta^{-1}(1-\theta)^{-1}$$
The prior we obtain this way is called the Haldane prior. The
function $\theta^{-1}(1-\theta)^{-1}$ has a little problem - the
integral over $I=[0, 1]$ is infinite, i.e., no matter what the
normalizing constant, it cannot be transformed into a proper pdf.
Actually, the Haldane prior is a proper pmf, which puts
probability 0.5 on $\theta=0$, 0.5 on $\theta=1$ and 0
probability on all other values for $\theta$. However, let's not get
carried away - for a continuous parameter $\theta$, priors which
don't correspond to a proper pdf are called improper priors.
Since, as noted before, all that matters for Bayesian inference is
the posterior distribution, improper priors are admissible, as long
as the posterior distribution is proper. In the case of the Haldane
prior, we can prove that the posterior pdf is proper if our sample
contains at least one success and one failure. Thus we can only use
the Haldane prior when we observe at least one head and one tail.
There's another sense in which the Haldane prior can be considered
non-informative: the mean of the posterior distribution is now
$\frac{\alpha + x}{\alpha + \beta + n}=\frac{x}{n}$, i.e., the
sample frequency of heads, which is the frequentist MLE estimate of
$\theta$ for the Binomial model of the coin flip problem. Also, the
credible intervals for $\theta$ correspond to the Wald confidence
intervals. Since frequentist methods don't specify a prior, one
could say that the Haldane prior is noninformative, or corresponds
to zero prior knowledge, because it leads to the "same" inference a
frequentist would make.
Finally, you could use a prior which doesn't depend on the
parametrization of the problem, i.e., the Jeffreys prior, which for
the Beta-Binomial model corresponds to
$$\alpha=\beta=\frac{1}{2} \Rightarrow \pi(\theta) \propto
\theta^{-\frac{1}{2}}(1-\theta)^{-\frac{1}{2}}$$
thus with an effective sample size of 1. The Jeffreys prior has the
advantage that it's invariant under reparametrization of the
parameter space. For example, the uniform prior assigns equal
probability to all values of $\theta$, the probability of the event
"head". However, you could decide to parametrize this model in terms
of log-odds $\lambda=log(\frac{\theta}{1-\theta})$ of event "head",
instead than $\theta$. What's the prior which expresses "maximum
ignorance" in terms of log-odds, i.e., which says that all possible
log-odds for event "head" are equiprobable? It's the Haldane prior,
as shown in this (slightly cryptic) answer. Instead, the
Jeffreys is invariant under all changes of metric. Jeffreys stated
that a prior which doesn't have this property, is in some way
informative because it contains information on the metric you used
to parametrize the problem. His prior doesn't.
To summarize, there's not just one unequivocal choice for a noninformative prior in the Beta-Binomial model. What you choose depends on what you mean as zero prior knowledge, and on the goals of your analysis. | Beta distribution on flipping a coin
The quotation is a "logical sleight-of-hand" (great expression!), as noted by @whuber in comments to the OP. The only thing we can really say after seeing that the coin has an head and a tail, is that |
17,428 | Beta distribution on flipping a coin | It's clearly incorrect. Observing 1 heads and 1 tails means that $p(\theta=0)=0$ (it's impossible to have an all-heads coin) and $p(\theta=1)=0$ (it's impossible to have an all-tails coin). The uniform distribution isn't consistent with this. What is consistent is a Beta(2,2). From the Bayesian solution to the coin-flip problem with a Laplace (i.e. uniform) prior on the $\theta$, the posterior probability is $p(\theta)={\rm Beta}(h+1,(N-h)+1)$. | Beta distribution on flipping a coin | It's clearly incorrect. Observing 1 heads and 1 tails means that $p(\theta=0)=0$ (it's impossible to have an all-heads coin) and $p(\theta=1)=0$ (it's impossible to have an all-tails coin). The unif | Beta distribution on flipping a coin
It's clearly incorrect. Observing 1 heads and 1 tails means that $p(\theta=0)=0$ (it's impossible to have an all-heads coin) and $p(\theta=1)=0$ (it's impossible to have an all-tails coin). The uniform distribution isn't consistent with this. What is consistent is a Beta(2,2). From the Bayesian solution to the coin-flip problem with a Laplace (i.e. uniform) prior on the $\theta$, the posterior probability is $p(\theta)={\rm Beta}(h+1,(N-h)+1)$. | Beta distribution on flipping a coin
It's clearly incorrect. Observing 1 heads and 1 tails means that $p(\theta=0)=0$ (it's impossible to have an all-heads coin) and $p(\theta=1)=0$ (it's impossible to have an all-tails coin). The unif |
17,429 | What is the benefit of the truncated normal distribution in initializing weights in a neural network? | I think its about saturation of the neurons. Think about you have an activation function like sigmoid.
If your weight val gets value >= 2 or <=-2 your neuron will not learn. So, if you truncate your normal distribution you will not have this issue(at least from the initialization) based on your variance. I think thats why, its better to use truncated normal in general. | What is the benefit of the truncated normal distribution in initializing weights in a neural network | I think its about saturation of the neurons. Think about you have an activation function like sigmoid.
If your weight val gets value >= 2 or <=-2 your neuron will not learn. So, if you truncate your | What is the benefit of the truncated normal distribution in initializing weights in a neural network?
I think its about saturation of the neurons. Think about you have an activation function like sigmoid.
If your weight val gets value >= 2 or <=-2 your neuron will not learn. So, if you truncate your normal distribution you will not have this issue(at least from the initialization) based on your variance. I think thats why, its better to use truncated normal in general. | What is the benefit of the truncated normal distribution in initializing weights in a neural network
I think its about saturation of the neurons. Think about you have an activation function like sigmoid.
If your weight val gets value >= 2 or <=-2 your neuron will not learn. So, if you truncate your |
17,430 | What is the benefit of the truncated normal distribution in initializing weights in a neural network? | The truncated normal distribution is better for the parameters to be close to 0, and it's better to keep the parameters close to 0. See this question: https://stackoverflow.com/q/34569903/3552975
Three reasons to keep the parameters small(Source: Probabilistic Deep Learning: with Python, Keras and Tensorflow Probability):
Experience shows that trained NNs often have small weights.
Smaller weights lead to less extreme outputs (in classification, less extreme probabilities), which is desirable for an untrained model.
It’s a known property of prediction models that adding a component to the loss function, which prefers small weights, often helps to get a higher prediction performance. This approach is also known as regularization or weight decay in non-Bayesian NNs.
And in this blog: A Gentle Introduction to Weight Constraints in Deep Learning, Dr. Jason Brownlee states that:
Smaller weights in a neural network can result in a model that is more stable and less likely to overfit the training dataset, in turn having better performance when making a prediction on new data.
If you employ ReLU you'd better make it with a slightly positive initial bias:
One should generally initialize weights with a small amount of noise for symmetry breaking, and to prevent 0 gradients. Since we're using ReLU neurons, it is also good practice to initialize them with a slightly positive initial bias to avoid "dead neurons". | What is the benefit of the truncated normal distribution in initializing weights in a neural network | The truncated normal distribution is better for the parameters to be close to 0, and it's better to keep the parameters close to 0. See this question: https://stackoverflow.com/q/34569903/3552975
Thr | What is the benefit of the truncated normal distribution in initializing weights in a neural network?
The truncated normal distribution is better for the parameters to be close to 0, and it's better to keep the parameters close to 0. See this question: https://stackoverflow.com/q/34569903/3552975
Three reasons to keep the parameters small(Source: Probabilistic Deep Learning: with Python, Keras and Tensorflow Probability):
Experience shows that trained NNs often have small weights.
Smaller weights lead to less extreme outputs (in classification, less extreme probabilities), which is desirable for an untrained model.
It’s a known property of prediction models that adding a component to the loss function, which prefers small weights, often helps to get a higher prediction performance. This approach is also known as regularization or weight decay in non-Bayesian NNs.
And in this blog: A Gentle Introduction to Weight Constraints in Deep Learning, Dr. Jason Brownlee states that:
Smaller weights in a neural network can result in a model that is more stable and less likely to overfit the training dataset, in turn having better performance when making a prediction on new data.
If you employ ReLU you'd better make it with a slightly positive initial bias:
One should generally initialize weights with a small amount of noise for symmetry breaking, and to prevent 0 gradients. Since we're using ReLU neurons, it is also good practice to initialize them with a slightly positive initial bias to avoid "dead neurons". | What is the benefit of the truncated normal distribution in initializing weights in a neural network
The truncated normal distribution is better for the parameters to be close to 0, and it's better to keep the parameters close to 0. See this question: https://stackoverflow.com/q/34569903/3552975
Thr |
17,431 | Use Pearson's correlation coefficient as optimization objective in machine learning | Maximizing correlation is useful when the output is highly noisy. In other words, the relationship between inputs and outputs is very weak. In such case, minimizing MSE will tend to make the output close to zero so that the predication error is the same as the variance of the training output.
Directly using correlation as objective function is possible for gradient descent approach (simply change it to minimizing minus correlation). However, I do not know how to optimize it with SGD approach, because the cost function and the gradient involves outputs of all training samples.
Another way to maximize correlation is to minimize MSE with constraining the output variance to be the same as training output variance. However, the constraint also involves all outputs thus there is no way (in my opinion) to take advantage of SGD optimizer.
EDIT:
In case the top layer of the neural network is a linear output layer, we can minimize MSE and then adjust the weights and bias in the linear layer to maximize the correlation. The adjustment can be done similarly to CCA (https://en.wikipedia.org/wiki/Canonical_analysis). | Use Pearson's correlation coefficient as optimization objective in machine learning | Maximizing correlation is useful when the output is highly noisy. In other words, the relationship between inputs and outputs is very weak. In such case, minimizing MSE will tend to make the output cl | Use Pearson's correlation coefficient as optimization objective in machine learning
Maximizing correlation is useful when the output is highly noisy. In other words, the relationship between inputs and outputs is very weak. In such case, minimizing MSE will tend to make the output close to zero so that the predication error is the same as the variance of the training output.
Directly using correlation as objective function is possible for gradient descent approach (simply change it to minimizing minus correlation). However, I do not know how to optimize it with SGD approach, because the cost function and the gradient involves outputs of all training samples.
Another way to maximize correlation is to minimize MSE with constraining the output variance to be the same as training output variance. However, the constraint also involves all outputs thus there is no way (in my opinion) to take advantage of SGD optimizer.
EDIT:
In case the top layer of the neural network is a linear output layer, we can minimize MSE and then adjust the weights and bias in the linear layer to maximize the correlation. The adjustment can be done similarly to CCA (https://en.wikipedia.org/wiki/Canonical_analysis). | Use Pearson's correlation coefficient as optimization objective in machine learning
Maximizing correlation is useful when the output is highly noisy. In other words, the relationship between inputs and outputs is very weak. In such case, minimizing MSE will tend to make the output cl |
17,432 | Use Pearson's correlation coefficient as optimization objective in machine learning | We use Pearson´s correlation in our research and it works well. In our case it is quite stable. Since it is a translation and scale invariant measure it is only useful if you want to predict shape, not precise values. Hence, it is useful if you don't know if your target is in the solution space of your model and you are only interested in the shape. On the contrary, MSE reduces the averaged distance between the prediction and the targets, so it tries to fit the data as much as possible. This is probably the reason why MSE is more widely used, because you are usually interested in predicting precise values. If you minimize the MSE, then the correlation will increase. | Use Pearson's correlation coefficient as optimization objective in machine learning | We use Pearson´s correlation in our research and it works well. In our case it is quite stable. Since it is a translation and scale invariant measure it is only useful if you want to predict shape, no | Use Pearson's correlation coefficient as optimization objective in machine learning
We use Pearson´s correlation in our research and it works well. In our case it is quite stable. Since it is a translation and scale invariant measure it is only useful if you want to predict shape, not precise values. Hence, it is useful if you don't know if your target is in the solution space of your model and you are only interested in the shape. On the contrary, MSE reduces the averaged distance between the prediction and the targets, so it tries to fit the data as much as possible. This is probably the reason why MSE is more widely used, because you are usually interested in predicting precise values. If you minimize the MSE, then the correlation will increase. | Use Pearson's correlation coefficient as optimization objective in machine learning
We use Pearson´s correlation in our research and it works well. In our case it is quite stable. Since it is a translation and scale invariant measure it is only useful if you want to predict shape, no |
17,433 | Use Pearson's correlation coefficient as optimization objective in machine learning | I've done research in the field of Content Based Image Retrieval, where the goal was to have an embedding that is correlated to some similarity measure. So in this situation you don't care for the distance between embeddings to have an particular value (matching some arbitrarily scaled similarity distance measure). You just want them correlated.
In some of the experiments pearson correlation loss (keras) was used as the cost function. I don't recall having any training difficulties with it (using Adam optimizer).
Although it was applied batch-wise (and not on all outputs), the model had improved correlation ("real" correlation over the entire test set) compared to logcosh cost function. | Use Pearson's correlation coefficient as optimization objective in machine learning | I've done research in the field of Content Based Image Retrieval, where the goal was to have an embedding that is correlated to some similarity measure. So in this situation you don't care for the dis | Use Pearson's correlation coefficient as optimization objective in machine learning
I've done research in the field of Content Based Image Retrieval, where the goal was to have an embedding that is correlated to some similarity measure. So in this situation you don't care for the distance between embeddings to have an particular value (matching some arbitrarily scaled similarity distance measure). You just want them correlated.
In some of the experiments pearson correlation loss (keras) was used as the cost function. I don't recall having any training difficulties with it (using Adam optimizer).
Although it was applied batch-wise (and not on all outputs), the model had improved correlation ("real" correlation over the entire test set) compared to logcosh cost function. | Use Pearson's correlation coefficient as optimization objective in machine learning
I've done research in the field of Content Based Image Retrieval, where the goal was to have an embedding that is correlated to some similarity measure. So in this situation you don't care for the dis |
17,434 | How odd is a cluster of plane accidents? | Summary: The first sentence in the quoted BBC paragraph is sloppy and misleading.
Even though previous answers and comments provided an excellent discussion already, I feel that the main question has not been answered satisfactorily.
So let us assume that a probability of a plane crash on any given day is $p=1/365$ and that the crashes are independent from each other. Let us further assume that one plane crashed on January 1st. When would the next plane crash?
Well, let us do a simple simulation: for each day for the next three years I will randomly decide if another plane crashed with probability $p$ and note the day of the next crash; I will repeat this procedure $100\,000$ times. Here is the resulting histogram:
In fact, the probability distribution is simply given by $\mathrm{Pr}(t) = (1-p)^t p$, where $t$ is the number of days. I plotted this theoretical distribution as a red line, and you can see that it fits well to the Monte Carlo histogram. Remark: if time were discretized in smaller and smaller bins, this distributions would converge to an exponential one; but it does not really matter for this discussion.
As many people have already remarked here, it is a decreasing curve. This means that the probability that the next plane crashes on the next day, January 2nd, is higher than the probability that the next plane will crash on any other given day, e.g. on January 2nd next year (the difference is almost three-fold: $0.27\%$ and $0.10\%$).
However, if you ask what is the probability that the next plane crashes in the next three days, the answer is $0.8\%$, but if you ask what is the probability that it will crash after three days, but in the next three years, then the answer is $94\%$. So, obviously, it is more likely that it will crash in the next three years (but after the first three days) than in the next three days. The confusion arises because when you say "clustered events" you refer to a very small initial chunk of the distribution, but when you say "widely spaced" events you refer to a large chunk of it. That is why even with a monotonically decreasing probability distribution it is surely possible that "clusters" (e.g. two plane crashes in three days) are very unlikely.
Here is another histogram to really get this point across. It is simply a sum of the previous histogram over several non-intersecting time periods: | How odd is a cluster of plane accidents? | Summary: The first sentence in the quoted BBC paragraph is sloppy and misleading.
Even though previous answers and comments provided an excellent discussion already, I feel that the main question has | How odd is a cluster of plane accidents?
Summary: The first sentence in the quoted BBC paragraph is sloppy and misleading.
Even though previous answers and comments provided an excellent discussion already, I feel that the main question has not been answered satisfactorily.
So let us assume that a probability of a plane crash on any given day is $p=1/365$ and that the crashes are independent from each other. Let us further assume that one plane crashed on January 1st. When would the next plane crash?
Well, let us do a simple simulation: for each day for the next three years I will randomly decide if another plane crashed with probability $p$ and note the day of the next crash; I will repeat this procedure $100\,000$ times. Here is the resulting histogram:
In fact, the probability distribution is simply given by $\mathrm{Pr}(t) = (1-p)^t p$, where $t$ is the number of days. I plotted this theoretical distribution as a red line, and you can see that it fits well to the Monte Carlo histogram. Remark: if time were discretized in smaller and smaller bins, this distributions would converge to an exponential one; but it does not really matter for this discussion.
As many people have already remarked here, it is a decreasing curve. This means that the probability that the next plane crashes on the next day, January 2nd, is higher than the probability that the next plane will crash on any other given day, e.g. on January 2nd next year (the difference is almost three-fold: $0.27\%$ and $0.10\%$).
However, if you ask what is the probability that the next plane crashes in the next three days, the answer is $0.8\%$, but if you ask what is the probability that it will crash after three days, but in the next three years, then the answer is $94\%$. So, obviously, it is more likely that it will crash in the next three years (but after the first three days) than in the next three days. The confusion arises because when you say "clustered events" you refer to a very small initial chunk of the distribution, but when you say "widely spaced" events you refer to a large chunk of it. That is why even with a monotonically decreasing probability distribution it is surely possible that "clusters" (e.g. two plane crashes in three days) are very unlikely.
Here is another histogram to really get this point across. It is simply a sum of the previous histogram over several non-intersecting time periods: | How odd is a cluster of plane accidents?
Summary: The first sentence in the quoted BBC paragraph is sloppy and misleading.
Even though previous answers and comments provided an excellent discussion already, I feel that the main question has |
17,435 | How odd is a cluster of plane accidents? | What the reporter is saying is that the random occurrence of a plane crash can be modelled as a Poisson process--a situation where the probability of an event occurring over some (small) interval is proportional to the length of said interval and where each occurrence in Independent of all others.
Is this a reasonable model for the scenario described?
Probably.
Sure, these events might not be 100% Independent since other pilots likely alter their behavior (if only very slightly) after a crash. [I don't know--perhaps a few pilots do some extra bit of simulator training or something like that]. Nevertheless, the assumption of Independence is still entirely reasonable.
What about clusters of plane crashes?
Yes. Given a Poisson process (or even some other random process), you would expect to see some clusters of occurrences.
In fact, as described by the Oxford Dictionary of Statistics in its entry for Poisson Process (which is a "mathematical description of randomness"):
[R]andomness usually gives rise to apparent clustering, despite the natural
expectation that randomness would lead to regularity.
For example, check out this simple bit of R code:
set.seed(123)
x <- runif(500)
y <- runif(500)
plot(x, y, pch=20, col='blue', main="A Random Distribution of Points")
which produces:
Even though we know this is a plot of random points, it sort of looks like there are some non-random bits to it--specifically, in some parts of the graph there are clumps of points while other parts are wide open. It's this same sort of behavior that the article is trying to describe (only with time series data and not spatial data).
UPDATE:
@JoelW.: So, for instance, let's say the probability of a plane crashing tomorrow (or any day for that matter) is "p" (and, let's say "p" is something like 1 in a hundred).
The reason why the next plane crash is more likely to occur tomorrow than it is more likely to occur in exactly a year (i.e. on July 26, 2015) is because the probability that the next crash is in exactly one year is equal to:
= Prob(crash tomorrow) * Prob(365 days with *no* crashes)
Make sense?
Ultimately, I think that the reason these things are Counter-Intuitive is because usually when we think of a phrase like: "The odds of a plane crash in one month compared with the odds of one happening tomorrow". We naturally don't immediately consider the 24-hour period that begins in exactly one month. Instead, we (or at least I do) tend to think of it in more, well, flexibly. So more like: a month ± a week. That and the fact that we forget about taking into account the odds of a crash not happening in the interim... (But again, maybe that's just me...).
Phew!
Additional Resources:
Wikipedia's article on the Clustering Illusion
A pdf which specifically mentions the "clustering" of plane crashes (on page 8) and briefly describes the mathematics of a Poisson process. | How odd is a cluster of plane accidents? | What the reporter is saying is that the random occurrence of a plane crash can be modelled as a Poisson process--a situation where the probability of an event occurring over some (small) interval is p | How odd is a cluster of plane accidents?
What the reporter is saying is that the random occurrence of a plane crash can be modelled as a Poisson process--a situation where the probability of an event occurring over some (small) interval is proportional to the length of said interval and where each occurrence in Independent of all others.
Is this a reasonable model for the scenario described?
Probably.
Sure, these events might not be 100% Independent since other pilots likely alter their behavior (if only very slightly) after a crash. [I don't know--perhaps a few pilots do some extra bit of simulator training or something like that]. Nevertheless, the assumption of Independence is still entirely reasonable.
What about clusters of plane crashes?
Yes. Given a Poisson process (or even some other random process), you would expect to see some clusters of occurrences.
In fact, as described by the Oxford Dictionary of Statistics in its entry for Poisson Process (which is a "mathematical description of randomness"):
[R]andomness usually gives rise to apparent clustering, despite the natural
expectation that randomness would lead to regularity.
For example, check out this simple bit of R code:
set.seed(123)
x <- runif(500)
y <- runif(500)
plot(x, y, pch=20, col='blue', main="A Random Distribution of Points")
which produces:
Even though we know this is a plot of random points, it sort of looks like there are some non-random bits to it--specifically, in some parts of the graph there are clumps of points while other parts are wide open. It's this same sort of behavior that the article is trying to describe (only with time series data and not spatial data).
UPDATE:
@JoelW.: So, for instance, let's say the probability of a plane crashing tomorrow (or any day for that matter) is "p" (and, let's say "p" is something like 1 in a hundred).
The reason why the next plane crash is more likely to occur tomorrow than it is more likely to occur in exactly a year (i.e. on July 26, 2015) is because the probability that the next crash is in exactly one year is equal to:
= Prob(crash tomorrow) * Prob(365 days with *no* crashes)
Make sense?
Ultimately, I think that the reason these things are Counter-Intuitive is because usually when we think of a phrase like: "The odds of a plane crash in one month compared with the odds of one happening tomorrow". We naturally don't immediately consider the 24-hour period that begins in exactly one month. Instead, we (or at least I do) tend to think of it in more, well, flexibly. So more like: a month ± a week. That and the fact that we forget about taking into account the odds of a crash not happening in the interim... (But again, maybe that's just me...).
Phew!
Additional Resources:
Wikipedia's article on the Clustering Illusion
A pdf which specifically mentions the "clustering" of plane crashes (on page 8) and briefly describes the mathematics of a Poisson process. | How odd is a cluster of plane accidents?
What the reporter is saying is that the random occurrence of a plane crash can be modelled as a Poisson process--a situation where the probability of an event occurring over some (small) interval is p |
17,436 | How odd is a cluster of plane accidents? | If the number of plane crashes is Poisson distributed (as he seems to be stating), the time between crashes has an exponential distribution. The pdf of the exponential distribution is a monotone decreasing function of time. Hence earlier crashes are more likely than later crashes. | How odd is a cluster of plane accidents? | If the number of plane crashes is Poisson distributed (as he seems to be stating), the time between crashes has an exponential distribution. The pdf of the exponential distribution is a monotone decre | How odd is a cluster of plane accidents?
If the number of plane crashes is Poisson distributed (as he seems to be stating), the time between crashes has an exponential distribution. The pdf of the exponential distribution is a monotone decreasing function of time. Hence earlier crashes are more likely than later crashes. | How odd is a cluster of plane accidents?
If the number of plane crashes is Poisson distributed (as he seems to be stating), the time between crashes has an exponential distribution. The pdf of the exponential distribution is a monotone decre |
17,437 | How odd is a cluster of plane accidents? | The other answers have already dealt with how independent events cluster. (Reading Gleick's Chaos, all those years ago, opened my eyes to this idea.)
But, in fact there is strong evidence that plane crashes are not independent events. Cialdini's Influence has a very good chapter on this (also mentioned here which has a couple of links to data; and I found an excerpt of that part of the book). Obviously this is highly controversial: it is basically saying that the more publicized an air crash is, the more likely it is to influence a pilot (consciously or unconsciously) to crash his plane. But the psychological explanations underlying the hypothesis seem plausible, and the data seems to support it too.
(Links to statistics-based debunking research would be welcome, in the comments.) | How odd is a cluster of plane accidents? | The other answers have already dealt with how independent events cluster. (Reading Gleick's Chaos, all those years ago, opened my eyes to this idea.)
But, in fact there is strong evidence that plane c | How odd is a cluster of plane accidents?
The other answers have already dealt with how independent events cluster. (Reading Gleick's Chaos, all those years ago, opened my eyes to this idea.)
But, in fact there is strong evidence that plane crashes are not independent events. Cialdini's Influence has a very good chapter on this (also mentioned here which has a couple of links to data; and I found an excerpt of that part of the book). Obviously this is highly controversial: it is basically saying that the more publicized an air crash is, the more likely it is to influence a pilot (consciously or unconsciously) to crash his plane. But the psychological explanations underlying the hypothesis seem plausible, and the data seems to support it too.
(Links to statistics-based debunking research would be welcome, in the comments.) | How odd is a cluster of plane accidents?
The other answers have already dealt with how independent events cluster. (Reading Gleick's Chaos, all those years ago, opened my eyes to this idea.)
But, in fact there is strong evidence that plane c |
17,438 | AIC, BIC and GCV: what is best for making decision in penalized regression methods? | I think of BIC as being preferred when there is a "true" low-dimensional model, which I think is never the case in empirical work. AIC is more in line with assuming that the more data we acquire the more complex a model can be. AIC using the effective degrees of freedom, in my experience, is a very good way to select the penalty parameter $\lambda$ because it is likely to optimize model performance in a new, independent, sample. | AIC, BIC and GCV: what is best for making decision in penalized regression methods? | I think of BIC as being preferred when there is a "true" low-dimensional model, which I think is never the case in empirical work. AIC is more in line with assuming that the more data we acquire the | AIC, BIC and GCV: what is best for making decision in penalized regression methods?
I think of BIC as being preferred when there is a "true" low-dimensional model, which I think is never the case in empirical work. AIC is more in line with assuming that the more data we acquire the more complex a model can be. AIC using the effective degrees of freedom, in my experience, is a very good way to select the penalty parameter $\lambda$ because it is likely to optimize model performance in a new, independent, sample. | AIC, BIC and GCV: what is best for making decision in penalized regression methods?
I think of BIC as being preferred when there is a "true" low-dimensional model, which I think is never the case in empirical work. AIC is more in line with assuming that the more data we acquire the |
17,439 | AIC, BIC and GCV: what is best for making decision in penalized regression methods? | My own thoughts on this aren't very collected, but here is a collection of points I'm aware of that might help.
The Bayesian interpretation of AIC is that it is a bias-corrected approximation to the expected log pointwise predictive density, i.e. the out-of-sample prediction error. This interpretation is laid out nicely in Gelman, Hwang, and Vehtari (2013) and also discussed briefly on Gelman's blog. Cross-validation is a different approximation to the same thing.
Meanwhile, BIC is an approximation to the "Bayes factor" under a particular prior (explained nicely in Raftery, 1999). This is almost the Bayesian analogue of a likelihood ratio.
What's interesting about AIC and BIC is that penalized regression also has a Bayesian interpretation, e.g. LASSO is the MAP estimate of Bayesian regression with independent Laplace priors on the coefficients. A bit more info in this previous question and a lot more in Kyung, Gill, Ghosh, and Casella (2010).
This suggests to me that you might get some mileage, or at least a more coherent research design, by thinking and modeling in Bayesian terms. I know this is a bit unusual in a lot of applications like high-dimensional machine learning, and also somewhat removed from the (in my opinion) more interpretable geometric and loss-function interpretations of regularization. At the very least, I rely heavily on the Bayesian interpretation to decide between AIC and BIC and to explain the difference to laymen, non-statistically-oriented co-workers/bosses, etc.
I know this doesn't speak much to cross-validation. One nice thing about Bayesian inference is that it produces approximate distributions of your parameters, rather than point estimates. This, I feel, can be used to sidestep the issue of measuring one's uncertainty about prediction error. However, if you're talking about using CV to estimate hyperparameters, e.g. $\lambda$ for LASSO, I again defer to Gelman:
selecting a tuning parameter by cross-validation is just a particular implementation of hierarchical Bayes. | AIC, BIC and GCV: what is best for making decision in penalized regression methods? | My own thoughts on this aren't very collected, but here is a collection of points I'm aware of that might help.
The Bayesian interpretation of AIC is that it is a bias-corrected approximation to the | AIC, BIC and GCV: what is best for making decision in penalized regression methods?
My own thoughts on this aren't very collected, but here is a collection of points I'm aware of that might help.
The Bayesian interpretation of AIC is that it is a bias-corrected approximation to the expected log pointwise predictive density, i.e. the out-of-sample prediction error. This interpretation is laid out nicely in Gelman, Hwang, and Vehtari (2013) and also discussed briefly on Gelman's blog. Cross-validation is a different approximation to the same thing.
Meanwhile, BIC is an approximation to the "Bayes factor" under a particular prior (explained nicely in Raftery, 1999). This is almost the Bayesian analogue of a likelihood ratio.
What's interesting about AIC and BIC is that penalized regression also has a Bayesian interpretation, e.g. LASSO is the MAP estimate of Bayesian regression with independent Laplace priors on the coefficients. A bit more info in this previous question and a lot more in Kyung, Gill, Ghosh, and Casella (2010).
This suggests to me that you might get some mileage, or at least a more coherent research design, by thinking and modeling in Bayesian terms. I know this is a bit unusual in a lot of applications like high-dimensional machine learning, and also somewhat removed from the (in my opinion) more interpretable geometric and loss-function interpretations of regularization. At the very least, I rely heavily on the Bayesian interpretation to decide between AIC and BIC and to explain the difference to laymen, non-statistically-oriented co-workers/bosses, etc.
I know this doesn't speak much to cross-validation. One nice thing about Bayesian inference is that it produces approximate distributions of your parameters, rather than point estimates. This, I feel, can be used to sidestep the issue of measuring one's uncertainty about prediction error. However, if you're talking about using CV to estimate hyperparameters, e.g. $\lambda$ for LASSO, I again defer to Gelman:
selecting a tuning parameter by cross-validation is just a particular implementation of hierarchical Bayes. | AIC, BIC and GCV: what is best for making decision in penalized regression methods?
My own thoughts on this aren't very collected, but here is a collection of points I'm aware of that might help.
The Bayesian interpretation of AIC is that it is a bias-corrected approximation to the |
17,440 | Stats: Relationship between Alpha and Beta | $\alpha$ and $\beta$ are related. I'll try to illustrate the point with a diagnostic test. Let's say that you have a diagnostic test that measures the level of a blood marker. It is known that people having a certain disease have lower levels of this marker compared to healthy people. It is immediately clear that you have to decide a cutoff value, below which a person is classified as "sick" whereas people with values above this cutoff are thought to be healthy. It is very likely, though, that the distribution of the bloodmarker varies considerably even within sick and healthy people. Some healthy persons might have very low blood marker levels, even though they are perfectly healthy. And some sick people have high levels of the blood marker even though they have the disease.
There are four possibilities that can occur:
a sick person is correctly identified as sick (true positive = TP)
a sick person is falsely classified as healthy (false negative = FN)
a healthy person is correctly identified as healthy (true negative =
TN)
a healthy person is falsely classified as sick (false positive =
FP)
These possibilities can be illustrated with a 2x2 table:
Sick Healthy
Test positive TP FP
Test negative FN TN
$\alpha$ denotes the false positive rate, which is $\alpha = FP/(FP + TN)$. $\beta$ is the false negative rate, which is $\beta = FN/(TP + FN)$. I wrote a simply R script to illustrate the situation graphically.
alphabeta <- function(mean.sick=100, sd.sick=10,
mean.healthy=130, sd.healthy=10, cutoff=120, n=10000,
side="below", do.plot=TRUE) {
popsick <- rnorm(n, mean=mean.sick, sd=sd.sick)
pophealthy <- rnorm(n, mean=mean.healthy, sd=sd.healthy)
if ( side == "below" ) {
truepos <- length(popsick[popsick <= cutoff])
falsepos <- length(pophealthy[pophealthy <= cutoff])
trueneg <- length(pophealthy[pophealthy > cutoff])
falseneg <- length(popsick[popsick > cutoff])
} else if ( side == "above" ) {
truepos <- length(popsick[popsick >= cutoff])
falsepos <- length(pophealthy[pophealthy >= cutoff])
trueneg <- length(pophealthy[pophealthy < cutoff])
falseneg <- length(popsick[popsick < cutoff])
}
twotable <- matrix(c(truepos, falsepos, falseneg, trueneg),
2, 2, byrow=T)
rownames(twotable) <- c("Test positive", "Test negative")
colnames(twotable) <- c("Sick", "Healthy")
spec <- twotable[2, 2]/(twotable[2, 2] + twotable[1, 2])
alpha <- 1 - spec
sens <- pow <- twotable[1, 1]/(twotable[1, 1] +
twotable[2, 1])
beta <- 1 - sens
pos.pred <- twotable[1,1]/(twotable[1,1] + twotable[1,2])
neg.pred <- twotable[2,2]/(twotable[2,2] + twotable[2,1])
if ( do.plot == TRUE ) {
dsick <- density(popsick)
dhealthy <- density(pophealthy)
par(mar=c(5.5, 4, 0.5, 0.5))
plot(range(c(dsick$x, dhealthy$x)), range(c(c(dsick$y,
dhealthy$y))), type = "n", xlab="", ylab="",
axes=FALSE)
box()
axis(1, at=mean(pophealthy),
lab=substitute(mu[H[0]]~paste("=", m, sep=""),
list(m=mean.healthy)), cex.axis=1.5, tck=0.02)
axis(1, at=mean(popsick),
lab=substitute(mu[H[1]] ~ paste("=", m, sep=""),
list(m=mean.sick)), cex.axis=1.5, tck=0.02)
axis(1, at=cutoff, lab=substitute(italic(paste("Cutoff=",
coff, sep="")), list(coff=cutoff)), pos=-0.004,
tick=FALSE, cex.axis=1.25)
lines(dhealthy, col = "steelblue", lwd=2)
if ( side == "below" ) {
polygon(c(cutoff, dhealthy$x[dhealthy$x<=cutoff],
cutoff), c(0, dhealthy$y[dhealthy$x<=cutoff],0),
col = "grey65")
} else if ( side == "above" ) {
polygon(c(cutoff, dhealthy$x[dhealthy$x>=cutoff],
cutoff), c(0, dhealthy$y[dhealthy$x>=cutoff],0),
col = "grey65")
}
lines(dsick, col = "red", lwd=2)
if ( side == "below" ) {
polygon(c(cutoff, dsick$x[dsick$x>cutoff], cutoff),
c(0, dsick$y[dsick$x>cutoff], 0) , col="grey90")
} else if ( side == "above" ) {
polygon(c(cutoff, dsick$x[dsick$x<=cutoff], cutoff),
c(0, dsick$y[dsick$x<=cutoff],0) , col="grey90")
}
legend("topleft",
legend=
(c(as.expression(substitute(alpha~paste("=", a),
list(a=round(alpha,3)))),
as.expression(substitute(beta~paste("=", b),
list(b=round(beta,3)))))), fill=c("grey65",
"grey90"), cex=1.2, bty="n")
abline(v=mean(popsick), lty=3)
abline(v=mean(pophealthy), lty=3)
abline(v=cutoff, lty=1, lwd=1.5)
abline(h=0)
}
#list(specificity=spec, sensitivity=sens, alpha=alpha, beta=beta, power=pow, positiv.predictive=pos.pred, negative.predictive=neg.pred)
c(alpha, beta)
}
Let's look at an example. We assume that the mean level of the blood marker among the sick people is 100 with a standard deviation of 10. Among the healthy people, the mean blood level is 140 with a standard deviation of 15. The clinician sets the cutoff at 120.
alphabeta(mean.sick=100, sd.sick=10, mean.healthy=140,
sd.healthy=15, cutoff=120, n=100000, do.plot=TRUE,
side="below")
Sick Healthy
Test positive 9764 901
Test negative 236 9099
You see that the shaded areas are in a relation with each other. In this case, $\alpha = 901/(901+ 9099) \approx 0.09$ and $\beta = 236/(236 + 9764)\approx 0.024$. But what happens if the clinician had set the cutoff differently? Let's set it a bit lower, to 105 and see what happens.
Sick Healthy
Test positive 6909 90
Test negative 3091 9910
Our $\alpha$ is very low now because almost no healthy people are diagnosed as sick. But our $\beta$ has increased, because sick people with a high blood marker level are now falsely classified as healthy.
Finally, let us look how $\alpha$ and $\beta$ change for different cutoffs:
cutoffs <- seq(0, 200, by=0.1)
cutoff.grid <- expand.grid(cutoffs)
plot.frame <- apply(cutoff.grid, MARGIN=1, FUN=alphabeta,
mean.sick=100, sd.sick=10, mean.healthy=140,
sd.healthy=15, n=100000, do.plot=FALSE, side="below")
plot(plot.frame[1,] ~ cutoffs, type="l", las=1,
xlab="Cutoff value", ylab="Alpha/Beta", lwd=2,
cex.axis=1.5, cex.lab=1.2)
lines(plot.frame[2,]~cutoffs, col="steelblue", lty=2, lwd=2)
legend("topleft", legend=c(expression(alpha),
expression(beta)), lwd=c(2,2),lty=c(1,2), col=c("black",
"steelblue"), bty="n", cex=1.2)
You can immediately see that the ratio of $\alpha$ and $\beta$ is not constant. What is also very important is the effect size. In this case, this would be the difference of the means of the blood marker levels among sick and healthy people. The greater the difference, the easier the two groups can be separated by a cutoff:
Here we have a "perfect" test in the sense that the cutoff of 150 discriminates the sick from the healthy.
Bonferroni adjustements
Bonferroni adjustments reduces the $\alpha$ error but inflate the type II error ($\beta$). This means that the error of making a false negative decision is increased while false positives are minimized. That's why the Bonferroni adjustment is often called conservative. In the graphs above, note how the $\beta$ increased when we lowered the cutoff from 120 to 105: it increased from $0.02$ to $0.31$. At the same time, $\alpha$ decreased from $0.09$ to $0.01$. | Stats: Relationship between Alpha and Beta | $\alpha$ and $\beta$ are related. I'll try to illustrate the point with a diagnostic test. Let's say that you have a diagnostic test that measures the level of a blood marker. It is known that people | Stats: Relationship between Alpha and Beta
$\alpha$ and $\beta$ are related. I'll try to illustrate the point with a diagnostic test. Let's say that you have a diagnostic test that measures the level of a blood marker. It is known that people having a certain disease have lower levels of this marker compared to healthy people. It is immediately clear that you have to decide a cutoff value, below which a person is classified as "sick" whereas people with values above this cutoff are thought to be healthy. It is very likely, though, that the distribution of the bloodmarker varies considerably even within sick and healthy people. Some healthy persons might have very low blood marker levels, even though they are perfectly healthy. And some sick people have high levels of the blood marker even though they have the disease.
There are four possibilities that can occur:
a sick person is correctly identified as sick (true positive = TP)
a sick person is falsely classified as healthy (false negative = FN)
a healthy person is correctly identified as healthy (true negative =
TN)
a healthy person is falsely classified as sick (false positive =
FP)
These possibilities can be illustrated with a 2x2 table:
Sick Healthy
Test positive TP FP
Test negative FN TN
$\alpha$ denotes the false positive rate, which is $\alpha = FP/(FP + TN)$. $\beta$ is the false negative rate, which is $\beta = FN/(TP + FN)$. I wrote a simply R script to illustrate the situation graphically.
alphabeta <- function(mean.sick=100, sd.sick=10,
mean.healthy=130, sd.healthy=10, cutoff=120, n=10000,
side="below", do.plot=TRUE) {
popsick <- rnorm(n, mean=mean.sick, sd=sd.sick)
pophealthy <- rnorm(n, mean=mean.healthy, sd=sd.healthy)
if ( side == "below" ) {
truepos <- length(popsick[popsick <= cutoff])
falsepos <- length(pophealthy[pophealthy <= cutoff])
trueneg <- length(pophealthy[pophealthy > cutoff])
falseneg <- length(popsick[popsick > cutoff])
} else if ( side == "above" ) {
truepos <- length(popsick[popsick >= cutoff])
falsepos <- length(pophealthy[pophealthy >= cutoff])
trueneg <- length(pophealthy[pophealthy < cutoff])
falseneg <- length(popsick[popsick < cutoff])
}
twotable <- matrix(c(truepos, falsepos, falseneg, trueneg),
2, 2, byrow=T)
rownames(twotable) <- c("Test positive", "Test negative")
colnames(twotable) <- c("Sick", "Healthy")
spec <- twotable[2, 2]/(twotable[2, 2] + twotable[1, 2])
alpha <- 1 - spec
sens <- pow <- twotable[1, 1]/(twotable[1, 1] +
twotable[2, 1])
beta <- 1 - sens
pos.pred <- twotable[1,1]/(twotable[1,1] + twotable[1,2])
neg.pred <- twotable[2,2]/(twotable[2,2] + twotable[2,1])
if ( do.plot == TRUE ) {
dsick <- density(popsick)
dhealthy <- density(pophealthy)
par(mar=c(5.5, 4, 0.5, 0.5))
plot(range(c(dsick$x, dhealthy$x)), range(c(c(dsick$y,
dhealthy$y))), type = "n", xlab="", ylab="",
axes=FALSE)
box()
axis(1, at=mean(pophealthy),
lab=substitute(mu[H[0]]~paste("=", m, sep=""),
list(m=mean.healthy)), cex.axis=1.5, tck=0.02)
axis(1, at=mean(popsick),
lab=substitute(mu[H[1]] ~ paste("=", m, sep=""),
list(m=mean.sick)), cex.axis=1.5, tck=0.02)
axis(1, at=cutoff, lab=substitute(italic(paste("Cutoff=",
coff, sep="")), list(coff=cutoff)), pos=-0.004,
tick=FALSE, cex.axis=1.25)
lines(dhealthy, col = "steelblue", lwd=2)
if ( side == "below" ) {
polygon(c(cutoff, dhealthy$x[dhealthy$x<=cutoff],
cutoff), c(0, dhealthy$y[dhealthy$x<=cutoff],0),
col = "grey65")
} else if ( side == "above" ) {
polygon(c(cutoff, dhealthy$x[dhealthy$x>=cutoff],
cutoff), c(0, dhealthy$y[dhealthy$x>=cutoff],0),
col = "grey65")
}
lines(dsick, col = "red", lwd=2)
if ( side == "below" ) {
polygon(c(cutoff, dsick$x[dsick$x>cutoff], cutoff),
c(0, dsick$y[dsick$x>cutoff], 0) , col="grey90")
} else if ( side == "above" ) {
polygon(c(cutoff, dsick$x[dsick$x<=cutoff], cutoff),
c(0, dsick$y[dsick$x<=cutoff],0) , col="grey90")
}
legend("topleft",
legend=
(c(as.expression(substitute(alpha~paste("=", a),
list(a=round(alpha,3)))),
as.expression(substitute(beta~paste("=", b),
list(b=round(beta,3)))))), fill=c("grey65",
"grey90"), cex=1.2, bty="n")
abline(v=mean(popsick), lty=3)
abline(v=mean(pophealthy), lty=3)
abline(v=cutoff, lty=1, lwd=1.5)
abline(h=0)
}
#list(specificity=spec, sensitivity=sens, alpha=alpha, beta=beta, power=pow, positiv.predictive=pos.pred, negative.predictive=neg.pred)
c(alpha, beta)
}
Let's look at an example. We assume that the mean level of the blood marker among the sick people is 100 with a standard deviation of 10. Among the healthy people, the mean blood level is 140 with a standard deviation of 15. The clinician sets the cutoff at 120.
alphabeta(mean.sick=100, sd.sick=10, mean.healthy=140,
sd.healthy=15, cutoff=120, n=100000, do.plot=TRUE,
side="below")
Sick Healthy
Test positive 9764 901
Test negative 236 9099
You see that the shaded areas are in a relation with each other. In this case, $\alpha = 901/(901+ 9099) \approx 0.09$ and $\beta = 236/(236 + 9764)\approx 0.024$. But what happens if the clinician had set the cutoff differently? Let's set it a bit lower, to 105 and see what happens.
Sick Healthy
Test positive 6909 90
Test negative 3091 9910
Our $\alpha$ is very low now because almost no healthy people are diagnosed as sick. But our $\beta$ has increased, because sick people with a high blood marker level are now falsely classified as healthy.
Finally, let us look how $\alpha$ and $\beta$ change for different cutoffs:
cutoffs <- seq(0, 200, by=0.1)
cutoff.grid <- expand.grid(cutoffs)
plot.frame <- apply(cutoff.grid, MARGIN=1, FUN=alphabeta,
mean.sick=100, sd.sick=10, mean.healthy=140,
sd.healthy=15, n=100000, do.plot=FALSE, side="below")
plot(plot.frame[1,] ~ cutoffs, type="l", las=1,
xlab="Cutoff value", ylab="Alpha/Beta", lwd=2,
cex.axis=1.5, cex.lab=1.2)
lines(plot.frame[2,]~cutoffs, col="steelblue", lty=2, lwd=2)
legend("topleft", legend=c(expression(alpha),
expression(beta)), lwd=c(2,2),lty=c(1,2), col=c("black",
"steelblue"), bty="n", cex=1.2)
You can immediately see that the ratio of $\alpha$ and $\beta$ is not constant. What is also very important is the effect size. In this case, this would be the difference of the means of the blood marker levels among sick and healthy people. The greater the difference, the easier the two groups can be separated by a cutoff:
Here we have a "perfect" test in the sense that the cutoff of 150 discriminates the sick from the healthy.
Bonferroni adjustements
Bonferroni adjustments reduces the $\alpha$ error but inflate the type II error ($\beta$). This means that the error of making a false negative decision is increased while false positives are minimized. That's why the Bonferroni adjustment is often called conservative. In the graphs above, note how the $\beta$ increased when we lowered the cutoff from 120 to 105: it increased from $0.02$ to $0.31$. At the same time, $\alpha$ decreased from $0.09$ to $0.01$. | Stats: Relationship between Alpha and Beta
$\alpha$ and $\beta$ are related. I'll try to illustrate the point with a diagnostic test. Let's say that you have a diagnostic test that measures the level of a blood marker. It is known that people |
17,441 | Stats: Relationship between Alpha and Beta | For others in the future:
In Sample Size estimation, the Ztotal is calculated by adding the Z corresponding to alpha and Z corresponding to power (1-beta). So mathematically, if sample size is kept constant, increasing Z for alpha means you decrease the Z for power by the SAME amount e.g., increasing Zalpha from 0.05 to 0.1 decreases Zpower by 0.05.
The difference is the Z for alpha is two-tailed while the Z for beta is 1-tailed. So, while the Z value changes by the same amount, but the probability % that this Z value corresponds to does not change by the same amount.
Example:
5% alpha (95% confidence) with 80% power (20% beta) gives the same sample size as
20% alpha (80% confidence) with 93.6% power (6.4% beta) rather than the 95% power we would have if the relationship were 1:1. | Stats: Relationship between Alpha and Beta | For others in the future:
In Sample Size estimation, the Ztotal is calculated by adding the Z corresponding to alpha and Z corresponding to power (1-beta). So mathematically, if sample size is kept c | Stats: Relationship between Alpha and Beta
For others in the future:
In Sample Size estimation, the Ztotal is calculated by adding the Z corresponding to alpha and Z corresponding to power (1-beta). So mathematically, if sample size is kept constant, increasing Z for alpha means you decrease the Z for power by the SAME amount e.g., increasing Zalpha from 0.05 to 0.1 decreases Zpower by 0.05.
The difference is the Z for alpha is two-tailed while the Z for beta is 1-tailed. So, while the Z value changes by the same amount, but the probability % that this Z value corresponds to does not change by the same amount.
Example:
5% alpha (95% confidence) with 80% power (20% beta) gives the same sample size as
20% alpha (80% confidence) with 93.6% power (6.4% beta) rather than the 95% power we would have if the relationship were 1:1. | Stats: Relationship between Alpha and Beta
For others in the future:
In Sample Size estimation, the Ztotal is calculated by adding the Z corresponding to alpha and Z corresponding to power (1-beta). So mathematically, if sample size is kept c |
17,442 | Stats: Relationship between Alpha and Beta | There is no general relation between alpha and beta.
It all depends on your test, take the simple exemple:
(Wikipedia)
In colloquial usage type I error can be thought of as "convicting an innocent person" and type II error "letting a guilty person go free".
A jury can be severe: no type II error, some type I
A jury can be "kind": no type I but some type II
A jury can be normal: some type I and some type II
A jury can be perfect: no error
In practice there is two antagonist effect:
When the quality of the test goes up, type I and type II error decrease until some point.
When a jury improves, he tends to give better judgment over both innocent and guilty people.
After some point the underlying problem appears in the building of the test. Type I or II are more important for the one who runs the test. With the jury exemple, type I errors are more important and so the law process is build to avoid type I. If there is any doubt the person is free. Intuitively this lead to a growth in type II error.
Concerning Bonferroni:
(Wikipedia again)
Bonferroni correction controls the probability of false positives only. The correction ordinarily comes at the cost of increasing the probability of producing false negatives, and consequently reducing statistical power. When testing a large number of hypotheses, this can result in large critical values. | Stats: Relationship between Alpha and Beta | There is no general relation between alpha and beta.
It all depends on your test, take the simple exemple:
(Wikipedia)
In colloquial usage type I error can be thought of as "convicting an innocent pe | Stats: Relationship between Alpha and Beta
There is no general relation between alpha and beta.
It all depends on your test, take the simple exemple:
(Wikipedia)
In colloquial usage type I error can be thought of as "convicting an innocent person" and type II error "letting a guilty person go free".
A jury can be severe: no type II error, some type I
A jury can be "kind": no type I but some type II
A jury can be normal: some type I and some type II
A jury can be perfect: no error
In practice there is two antagonist effect:
When the quality of the test goes up, type I and type II error decrease until some point.
When a jury improves, he tends to give better judgment over both innocent and guilty people.
After some point the underlying problem appears in the building of the test. Type I or II are more important for the one who runs the test. With the jury exemple, type I errors are more important and so the law process is build to avoid type I. If there is any doubt the person is free. Intuitively this lead to a growth in type II error.
Concerning Bonferroni:
(Wikipedia again)
Bonferroni correction controls the probability of false positives only. The correction ordinarily comes at the cost of increasing the probability of producing false negatives, and consequently reducing statistical power. When testing a large number of hypotheses, this can result in large critical values. | Stats: Relationship between Alpha and Beta
There is no general relation between alpha and beta.
It all depends on your test, take the simple exemple:
(Wikipedia)
In colloquial usage type I error can be thought of as "convicting an innocent pe |
17,443 | Does Poisson Regression have an error term? | I think the problem that's confusing you is that you're used to having an additive error. Most models won't.
Think of linear regression not as a linear mean with an additive error, but as the response being conditionally normal:
$$(Y|X) \sim \operatorname{N}(X\beta,\sigma^2I)$$
Then the similarities to GLMs, in particular, to Poisson regression and logisitic regression are more clear.
Because of the nice properties of the normal, the normal case can be written in terms of the mean and an additive error. This is not always so nice with other models and it makes sense to stick to the distributional form for the model, or at least to write about the mean and variance of $(Y|X)$ rather than writing a model for $\operatorname{E}(Y|X)$ and trying to describe the characteristics of $Y-\operatorname{E}(Y|X)$.
[You can take any particular combination of predictors and write the response variable in terms of its expectation and a deviation from that - an 'error' if you will - but it's not particularly enlightening when its a different object from every other combination of predictors. It's usually more informative and more intuitive to just write the response as a distribution that is a function of the predictors than in deviation-from-expectation form.]
So while you can write it 'with an error term' it's just less convenient and conceptually harder to do so than to do other things. | Does Poisson Regression have an error term? | I think the problem that's confusing you is that you're used to having an additive error. Most models won't.
Think of linear regression not as a linear mean with an additive error, but as the response | Does Poisson Regression have an error term?
I think the problem that's confusing you is that you're used to having an additive error. Most models won't.
Think of linear regression not as a linear mean with an additive error, but as the response being conditionally normal:
$$(Y|X) \sim \operatorname{N}(X\beta,\sigma^2I)$$
Then the similarities to GLMs, in particular, to Poisson regression and logisitic regression are more clear.
Because of the nice properties of the normal, the normal case can be written in terms of the mean and an additive error. This is not always so nice with other models and it makes sense to stick to the distributional form for the model, or at least to write about the mean and variance of $(Y|X)$ rather than writing a model for $\operatorname{E}(Y|X)$ and trying to describe the characteristics of $Y-\operatorname{E}(Y|X)$.
[You can take any particular combination of predictors and write the response variable in terms of its expectation and a deviation from that - an 'error' if you will - but it's not particularly enlightening when its a different object from every other combination of predictors. It's usually more informative and more intuitive to just write the response as a distribution that is a function of the predictors than in deviation-from-expectation form.]
So while you can write it 'with an error term' it's just less convenient and conceptually harder to do so than to do other things. | Does Poisson Regression have an error term?
I think the problem that's confusing you is that you're used to having an additive error. Most models won't.
Think of linear regression not as a linear mean with an additive error, but as the response |
17,444 | Open source Java library for statistics at the level offered by a graduate statistics course | When I am forced to use java for basic statistics, apache commons math is the way to go. For plots, I use and recommend JFreeChart. The latter is widely spread, so stackoverflow even has a populated tag for it.
Edit
If one looks for a suite, then maybe Deducer is an option. The GUI is based on JGR meanwhile the statistical parts are called in R. It seems to be extendable both via R and java. One could e.g. skip the calls to the Rengine but call referenced java libraries instead. But I admit, I did not try it yet.
As far as I have understood the OP, the optimum would be something like Rapidminer for Statistics, since Rapidminer is a pure java framework which supports GUI access (including visualizations), usage as library and custom plugin development. To the best of my knowledge, something like that for statistics does not exist. I do not recommend Rapidminer for that particular task, because to the best of my knowledge it only includes the most basic statistical tests. The visualizations have been extended lately, but I cannot estimate how customizable they are now. | Open source Java library for statistics at the level offered by a graduate statistics course | When I am forced to use java for basic statistics, apache commons math is the way to go. For plots, I use and recommend JFreeChart. The latter is widely spread, so stackoverflow even has a populated t | Open source Java library for statistics at the level offered by a graduate statistics course
When I am forced to use java for basic statistics, apache commons math is the way to go. For plots, I use and recommend JFreeChart. The latter is widely spread, so stackoverflow even has a populated tag for it.
Edit
If one looks for a suite, then maybe Deducer is an option. The GUI is based on JGR meanwhile the statistical parts are called in R. It seems to be extendable both via R and java. One could e.g. skip the calls to the Rengine but call referenced java libraries instead. But I admit, I did not try it yet.
As far as I have understood the OP, the optimum would be something like Rapidminer for Statistics, since Rapidminer is a pure java framework which supports GUI access (including visualizations), usage as library and custom plugin development. To the best of my knowledge, something like that for statistics does not exist. I do not recommend Rapidminer for that particular task, because to the best of my knowledge it only includes the most basic statistical tests. The visualizations have been extended lately, but I cannot estimate how customizable they are now. | Open source Java library for statistics at the level offered by a graduate statistics course
When I am forced to use java for basic statistics, apache commons math is the way to go. For plots, I use and recommend JFreeChart. The latter is widely spread, so stackoverflow even has a populated t |
17,445 | Open source Java library for statistics at the level offered by a graduate statistics course | Check out Suan Shu: NumericalMethod.com. It is not free in general, but it is free for academic use. | Open source Java library for statistics at the level offered by a graduate statistics course | Check out Suan Shu: NumericalMethod.com. It is not free in general, but it is free for academic use. | Open source Java library for statistics at the level offered by a graduate statistics course
Check out Suan Shu: NumericalMethod.com. It is not free in general, but it is free for academic use. | Open source Java library for statistics at the level offered by a graduate statistics course
Check out Suan Shu: NumericalMethod.com. It is not free in general, but it is free for academic use. |
17,446 | Open source Java library for statistics at the level offered by a graduate statistics course | Similar to steffen's suggestion of RapidMiner, you might want to consider Weka. It may be geared more specifically to machine learning than you are hoping for though. It has lots of algorithms for tasks like clustering, classification, and regression. Weka has a GUI, but it can also be used as a software library as well. I've seen histograms in the GUI but I'm not sure if it's easy to reuse them through the library or not. | Open source Java library for statistics at the level offered by a graduate statistics course | Similar to steffen's suggestion of RapidMiner, you might want to consider Weka. It may be geared more specifically to machine learning than you are hoping for though. It has lots of algorithms for t | Open source Java library for statistics at the level offered by a graduate statistics course
Similar to steffen's suggestion of RapidMiner, you might want to consider Weka. It may be geared more specifically to machine learning than you are hoping for though. It has lots of algorithms for tasks like clustering, classification, and regression. Weka has a GUI, but it can also be used as a software library as well. I've seen histograms in the GUI but I'm not sure if it's easy to reuse them through the library or not. | Open source Java library for statistics at the level offered by a graduate statistics course
Similar to steffen's suggestion of RapidMiner, you might want to consider Weka. It may be geared more specifically to machine learning than you are hoping for though. It has lots of algorithms for t |
17,447 | Open source Java library for statistics at the level offered by a graduate statistics course | DataMelt computing environment has many Java statistical libraries almost for any topic. You can use it using Jython as advocated on the web site, but I use it with Java and Groovy.
I can say more: the DataMelt project covers the following statistical topics:
Random numbers
Most popular discrete and continues distributions
Descriptive statistical analysis
Data fit (linear and non-linear)
Various statistical tests
Histograms in 2D and 3D
Here is a non-linear regression example using log-likelihood approach to fit data with errors:
The package is free. | Open source Java library for statistics at the level offered by a graduate statistics course | DataMelt computing environment has many Java statistical libraries almost for any topic. You can use it using Jython as advocated on the web site, but I use it with Java and Groovy.
I can say more: th | Open source Java library for statistics at the level offered by a graduate statistics course
DataMelt computing environment has many Java statistical libraries almost for any topic. You can use it using Jython as advocated on the web site, but I use it with Java and Groovy.
I can say more: the DataMelt project covers the following statistical topics:
Random numbers
Most popular discrete and continues distributions
Descriptive statistical analysis
Data fit (linear and non-linear)
Various statistical tests
Histograms in 2D and 3D
Here is a non-linear regression example using log-likelihood approach to fit data with errors:
The package is free. | Open source Java library for statistics at the level offered by a graduate statistics course
DataMelt computing environment has many Java statistical libraries almost for any topic. You can use it using Jython as advocated on the web site, but I use it with Java and Groovy.
I can say more: th |
17,448 | Open source Java library for statistics at the level offered by a graduate statistics course | Try
http://www.roguewave.com/Portals/0/products/imsl-numerical-libraries/java-library/docs/5.0.1/api/overview-summary.html
It is well documented and provides a lot of useful statistical and mathematical functions.
But unfortunately it is not open source. So if that does not bother you, then the library should be ok.
I do not know however, if it provides graphical output. | Open source Java library for statistics at the level offered by a graduate statistics course | Try
http://www.roguewave.com/Portals/0/products/imsl-numerical-libraries/java-library/docs/5.0.1/api/overview-summary.html
It is well documented and provides a lot of useful statistical and mathemati | Open source Java library for statistics at the level offered by a graduate statistics course
Try
http://www.roguewave.com/Portals/0/products/imsl-numerical-libraries/java-library/docs/5.0.1/api/overview-summary.html
It is well documented and provides a lot of useful statistical and mathematical functions.
But unfortunately it is not open source. So if that does not bother you, then the library should be ok.
I do not know however, if it provides graphical output. | Open source Java library for statistics at the level offered by a graduate statistics course
Try
http://www.roguewave.com/Portals/0/products/imsl-numerical-libraries/java-library/docs/5.0.1/api/overview-summary.html
It is well documented and provides a lot of useful statistical and mathemati |
17,449 | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems? | The Poisson process involves a "memoryless" waiting time until the arrival of the next customer. Suppose the average time from one customer to the next is $\theta$. A memoryless continuous probability distribution until the next arrival is one in which the probability of waiting an additional minute, or second, or hour, etc., until the next arrival, does not depend on how long you've been waiting since the last one. That you've already waited five minutes since the last arrival does not make it more likely that a customer will arrive in the next minute, than it would be if you'd only waited 10 seconds since the last arrival.
This automatically implies that the waiting time $T$ until the next arrival satisfies $\Pr(T>t) = e^{-t/\theta}$, i.e., it's an exponential distribution.
And that in turn can be shown to imply that the number $X$ of customers arriving during any time interval of length $t$ satisfies $\Pr(X=x) = \dfrac{e^{-t/\theta} (t/\theta)^x}{x!}$, i.e. it has a Poisson distribution with expected value $t/\theta$. Moreover, it implies that the numbers of customers arriving in non-overlapping time intervals are probabilistically independent.
So memorylessness of waiting times leads to the Poisson process. | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems? | The Poisson process involves a "memoryless" waiting time until the arrival of the next customer. Suppose the average time from one customer to the next is $\theta$. A memoryless continuous probabili | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems?
The Poisson process involves a "memoryless" waiting time until the arrival of the next customer. Suppose the average time from one customer to the next is $\theta$. A memoryless continuous probability distribution until the next arrival is one in which the probability of waiting an additional minute, or second, or hour, etc., until the next arrival, does not depend on how long you've been waiting since the last one. That you've already waited five minutes since the last arrival does not make it more likely that a customer will arrive in the next minute, than it would be if you'd only waited 10 seconds since the last arrival.
This automatically implies that the waiting time $T$ until the next arrival satisfies $\Pr(T>t) = e^{-t/\theta}$, i.e., it's an exponential distribution.
And that in turn can be shown to imply that the number $X$ of customers arriving during any time interval of length $t$ satisfies $\Pr(X=x) = \dfrac{e^{-t/\theta} (t/\theta)^x}{x!}$, i.e. it has a Poisson distribution with expected value $t/\theta$. Moreover, it implies that the numbers of customers arriving in non-overlapping time intervals are probabilistically independent.
So memorylessness of waiting times leads to the Poisson process. | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems?
The Poisson process involves a "memoryless" waiting time until the arrival of the next customer. Suppose the average time from one customer to the next is $\theta$. A memoryless continuous probabili |
17,450 | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems? | Pretty much any intro to queuing theory or stochastic processes book will cover this, e.g., Ross, Stochastic Processes, or the Kleinrock, Queuing Theory.
For an outline of a proof that memoryless arrivals lead to an exponential dist'n:
Let G(x) = P(X > x) = 1 - F(x). Now, if the distribution is memoryless,
G(s+t) = G(s)G(t)
i.e., the probability that x > s+t = the probability that it is greater than s, and that, now that it is greater than s, it's greater than (s+t). The memoryless property means that the second (conditional) probability is equal to the probability that a different r.v. with the same distribution > t.
To quote Ross:
"The only solutions of the above equation that satisfy any sort of reasonable conditions, (such as monotonicity, right or left continuity, or even measurability), are of the form:"
G(x) = exp(-ax) for some suitable value of a.
and we are at the Exponential distribution. | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems? | Pretty much any intro to queuing theory or stochastic processes book will cover this, e.g., Ross, Stochastic Processes, or the Kleinrock, Queuing Theory.
For an outline of a proof that memoryless ar | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems?
Pretty much any intro to queuing theory or stochastic processes book will cover this, e.g., Ross, Stochastic Processes, or the Kleinrock, Queuing Theory.
For an outline of a proof that memoryless arrivals lead to an exponential dist'n:
Let G(x) = P(X > x) = 1 - F(x). Now, if the distribution is memoryless,
G(s+t) = G(s)G(t)
i.e., the probability that x > s+t = the probability that it is greater than s, and that, now that it is greater than s, it's greater than (s+t). The memoryless property means that the second (conditional) probability is equal to the probability that a different r.v. with the same distribution > t.
To quote Ross:
"The only solutions of the above equation that satisfy any sort of reasonable conditions, (such as monotonicity, right or left continuity, or even measurability), are of the form:"
G(x) = exp(-ax) for some suitable value of a.
and we are at the Exponential distribution. | Why is the Poisson distribution chosen to model arrival processes in Queueing theory problems?
Pretty much any intro to queuing theory or stochastic processes book will cover this, e.g., Ross, Stochastic Processes, or the Kleinrock, Queuing Theory.
For an outline of a proof that memoryless ar |
17,451 | Epoch Vs Iteration in CNN training | One iteration means one batch processed.
One epoch means all data processed one times.
So one epoch is counted when (batch_size * number_iteration) >= number_data | Epoch Vs Iteration in CNN training | One iteration means one batch processed.
One epoch means all data processed one times.
So one epoch is counted when (batch_size * number_iteration) >= number_data | Epoch Vs Iteration in CNN training
One iteration means one batch processed.
One epoch means all data processed one times.
So one epoch is counted when (batch_size * number_iteration) >= number_data | Epoch Vs Iteration in CNN training
One iteration means one batch processed.
One epoch means all data processed one times.
So one epoch is counted when (batch_size * number_iteration) >= number_data |
17,452 | Definition of Regressor | Yes, your understanding is correct. Feature, independent variable, explanatory variable, regressor, covariate, or predictor are all names of the variables that are used to predict the target, outcome, dependent variable, regressand, or response. The terminology is ambiguous as it comes from different fields: statistics, econometrics, and machine learning. | Definition of Regressor | Yes, your understanding is correct. Feature, independent variable, explanatory variable, regressor, covariate, or predictor are all names of the variables that are used to predict the target, outcome, | Definition of Regressor
Yes, your understanding is correct. Feature, independent variable, explanatory variable, regressor, covariate, or predictor are all names of the variables that are used to predict the target, outcome, dependent variable, regressand, or response. The terminology is ambiguous as it comes from different fields: statistics, econometrics, and machine learning. | Definition of Regressor
Yes, your understanding is correct. Feature, independent variable, explanatory variable, regressor, covariate, or predictor are all names of the variables that are used to predict the target, outcome, |
17,453 | Definition of Regressor | An explanatory variable is the variable in its raw form. A regressor is the variable as it appears in a regression equation. Hence, the regressor is the explanatory variable if used as is, but its transformation if any transformations are applied. I think that the term 'regressor' applies specifically to regression equations, and would not apply otherwise. | Definition of Regressor | An explanatory variable is the variable in its raw form. A regressor is the variable as it appears in a regression equation. Hence, the regressor is the explanatory variable if used as is, but its t | Definition of Regressor
An explanatory variable is the variable in its raw form. A regressor is the variable as it appears in a regression equation. Hence, the regressor is the explanatory variable if used as is, but its transformation if any transformations are applied. I think that the term 'regressor' applies specifically to regression equations, and would not apply otherwise. | Definition of Regressor
An explanatory variable is the variable in its raw form. A regressor is the variable as it appears in a regression equation. Hence, the regressor is the explanatory variable if used as is, but its t |
17,454 | QQ plot looks normal but Shapiro-Wilk test says otherwise | You do not have a problem here. Your data my be slightly non-normal, but it is normal enough that it shouldn't pose any problems. Many researchers do statistical tests assuming normality with far less normal data than those that you have.
I would trust your eyes. The density and Q-Q plots look reasonable, despite some slight positive skew on the tails. In my opinion, you do not need to worry about non-normality for these data.
You have an N of about 350, and p-values are very dependent on sample sizes. With a large sample, almost anything can be significant. This has been discussed here.
There are some incredible answers on this very popular post that basically comes to the conclusion that conducting a null-hypothesis significance test for non-normality is "essentially useless." The accepted answer on that post is a fabulous demonstration that, even when data were generated from a nearly Gaussian process, a high enough sample size makes the non-normal test significant.
Sorry, I realized that I linked to a post you had mentioned in your original question. My conclusion still stands, though: Your data are not so non-normal that it should pose problems. | QQ plot looks normal but Shapiro-Wilk test says otherwise | You do not have a problem here. Your data my be slightly non-normal, but it is normal enough that it shouldn't pose any problems. Many researchers do statistical tests assuming normality with far less | QQ plot looks normal but Shapiro-Wilk test says otherwise
You do not have a problem here. Your data my be slightly non-normal, but it is normal enough that it shouldn't pose any problems. Many researchers do statistical tests assuming normality with far less normal data than those that you have.
I would trust your eyes. The density and Q-Q plots look reasonable, despite some slight positive skew on the tails. In my opinion, you do not need to worry about non-normality for these data.
You have an N of about 350, and p-values are very dependent on sample sizes. With a large sample, almost anything can be significant. This has been discussed here.
There are some incredible answers on this very popular post that basically comes to the conclusion that conducting a null-hypothesis significance test for non-normality is "essentially useless." The accepted answer on that post is a fabulous demonstration that, even when data were generated from a nearly Gaussian process, a high enough sample size makes the non-normal test significant.
Sorry, I realized that I linked to a post you had mentioned in your original question. My conclusion still stands, though: Your data are not so non-normal that it should pose problems. | QQ plot looks normal but Shapiro-Wilk test says otherwise
You do not have a problem here. Your data my be slightly non-normal, but it is normal enough that it shouldn't pose any problems. Many researchers do statistical tests assuming normality with far less |
17,455 | QQ plot looks normal but Shapiro-Wilk test says otherwise | Your distribution is not normal. Look at the tails (or lack thereof). Below is what you would expect from a normal QQ plot.
Refer to this post on how to interpret various QQ plots.
Keep in mind that while a distribution may not technically be normal, it may be normal enough to qualify for algorithms which require normalcy. | QQ plot looks normal but Shapiro-Wilk test says otherwise | Your distribution is not normal. Look at the tails (or lack thereof). Below is what you would expect from a normal QQ plot.
Refer to this post on how to interpret various QQ plots.
Keep in mind tha | QQ plot looks normal but Shapiro-Wilk test says otherwise
Your distribution is not normal. Look at the tails (or lack thereof). Below is what you would expect from a normal QQ plot.
Refer to this post on how to interpret various QQ plots.
Keep in mind that while a distribution may not technically be normal, it may be normal enough to qualify for algorithms which require normalcy. | QQ plot looks normal but Shapiro-Wilk test says otherwise
Your distribution is not normal. Look at the tails (or lack thereof). Below is what you would expect from a normal QQ plot.
Refer to this post on how to interpret various QQ plots.
Keep in mind tha |
17,456 | Do we need to set training set and testing set for clustering? | Yes, because clustering may also suffer from over-fitting problem. For example, increasing number of clusters will always "increase the performance".
Here is one demo using K-Means clustering:
The objective function of K-means is
$$
J=\sum_{i=1}^{k}\sum_{j=1}^{n}\|x_i^{(j)}-c_j\|^2
$$
With such objective, the lower $J$ means "better" model.
Suppose we have following data (iris data), choosing number of cluster as $4$ will always "better" than choosing number of cluster as $3$. Then choosing $5$ clusters will be better than $4$ clusters. We can continue on this track and end up with $J=0$ cost: just make number of the cluster equal to number of the data points and place all the cluster center on the corresponding the points.
d=iris[,c(3,4)]
res4=kmeans(d, 4,nstart=20)
res3=kmeans(d, 3,nstart=20)
par(mfrow=c(1,2))
plot(d,col=factor(res4$cluster),
main=paste("4 clusters J=",round(res4$tot.withinss,4)))
plot(d,col=factor(res3$cluster),
main=paste("3 clusters J=",round(res3$tot.withinss,4)))
If we have hold off data for testing, it will prevent us to over-fit. The same example, suppose we are choosing large number clusters and put every cluster center to the training data points. The testing error will be large, because testing data points will not overlap with the training data. | Do we need to set training set and testing set for clustering? | Yes, because clustering may also suffer from over-fitting problem. For example, increasing number of clusters will always "increase the performance".
Here is one demo using K-Means clustering:
The ob | Do we need to set training set and testing set for clustering?
Yes, because clustering may also suffer from over-fitting problem. For example, increasing number of clusters will always "increase the performance".
Here is one demo using K-Means clustering:
The objective function of K-means is
$$
J=\sum_{i=1}^{k}\sum_{j=1}^{n}\|x_i^{(j)}-c_j\|^2
$$
With such objective, the lower $J$ means "better" model.
Suppose we have following data (iris data), choosing number of cluster as $4$ will always "better" than choosing number of cluster as $3$. Then choosing $5$ clusters will be better than $4$ clusters. We can continue on this track and end up with $J=0$ cost: just make number of the cluster equal to number of the data points and place all the cluster center on the corresponding the points.
d=iris[,c(3,4)]
res4=kmeans(d, 4,nstart=20)
res3=kmeans(d, 3,nstart=20)
par(mfrow=c(1,2))
plot(d,col=factor(res4$cluster),
main=paste("4 clusters J=",round(res4$tot.withinss,4)))
plot(d,col=factor(res3$cluster),
main=paste("3 clusters J=",round(res3$tot.withinss,4)))
If we have hold off data for testing, it will prevent us to over-fit. The same example, suppose we are choosing large number clusters and put every cluster center to the training data points. The testing error will be large, because testing data points will not overlap with the training data. | Do we need to set training set and testing set for clustering?
Yes, because clustering may also suffer from over-fitting problem. For example, increasing number of clusters will always "increase the performance".
Here is one demo using K-Means clustering:
The ob |
17,457 | Do we need to set training set and testing set for clustering? | No, this will usually not be possible.
There are very few clusterings that you could use like a classifier. Only with k-means, PAM etc. you could evaluate the "generalization", but clustering has become much more diverse (and interesting) since. And in fact, even the old hierarchical clustering won't generalize well to 'new' data. Clustering isn't classification. Many methods from classification do not transfer well to clustering; including hyperparameter optimization.
If you have only partially labeled data, you can use these labels to optimize parameters. But the general scenario of clustering will be that you want to learn more about your data set; so you run clustering several times, investigate the interesting clusters (because usually, some clusters clearly are too small or too large to be interesting!) and note down some of the insights you got. Clustering is a tool to help the human explore a data set, not a automatic thing. But you will not "deploy" a clustering. They are too unreliable, and a single clustering will never "tell the whole story". | Do we need to set training set and testing set for clustering? | No, this will usually not be possible.
There are very few clusterings that you could use like a classifier. Only with k-means, PAM etc. you could evaluate the "generalization", but clustering has beco | Do we need to set training set and testing set for clustering?
No, this will usually not be possible.
There are very few clusterings that you could use like a classifier. Only with k-means, PAM etc. you could evaluate the "generalization", but clustering has become much more diverse (and interesting) since. And in fact, even the old hierarchical clustering won't generalize well to 'new' data. Clustering isn't classification. Many methods from classification do not transfer well to clustering; including hyperparameter optimization.
If you have only partially labeled data, you can use these labels to optimize parameters. But the general scenario of clustering will be that you want to learn more about your data set; so you run clustering several times, investigate the interesting clusters (because usually, some clusters clearly are too small or too large to be interesting!) and note down some of the insights you got. Clustering is a tool to help the human explore a data set, not a automatic thing. But you will not "deploy" a clustering. They are too unreliable, and a single clustering will never "tell the whole story". | Do we need to set training set and testing set for clustering?
No, this will usually not be possible.
There are very few clusterings that you could use like a classifier. Only with k-means, PAM etc. you could evaluate the "generalization", but clustering has beco |
17,458 | Do we need to set training set and testing set for clustering? | Usually you split your data into train and test set when you want to evaluate the performance of your model in the train and test set. In order to do this, you need to know a priori in which cluster every observation belongs to, which means that you know exactly how many clusters there are in your data (equivalently the number of clusters isn't stochastic). Consequently, this means that you have data from let's say k populations. As you can see this isn't a clustering problem but a classification problem. | Do we need to set training set and testing set for clustering? | Usually you split your data into train and test set when you want to evaluate the performance of your model in the train and test set. In order to do this, you need to know a priori in which cluster e | Do we need to set training set and testing set for clustering?
Usually you split your data into train and test set when you want to evaluate the performance of your model in the train and test set. In order to do this, you need to know a priori in which cluster every observation belongs to, which means that you know exactly how many clusters there are in your data (equivalently the number of clusters isn't stochastic). Consequently, this means that you have data from let's say k populations. As you can see this isn't a clustering problem but a classification problem. | Do we need to set training set and testing set for clustering?
Usually you split your data into train and test set when you want to evaluate the performance of your model in the train and test set. In order to do this, you need to know a priori in which cluster e |
17,459 | Do we need to set training set and testing set for clustering? | The sample is not normally split into training and test set in clustering, because, as said in other answers, the test set will not have "true labels" available, so you can't check predictions from the training set on it.
There are however some uses for data set splits in cluster analysis. Particularly one may be interested in whether a clustering structure that is found on one part of the data set corresponds to what goes on in the other half. This isn't quite as easy to formalise though as in supervised classification. We have a paper on this here.
Ullmann, T., Hennig, C., & Boulesteix, A.-L. (2022). Validation of cluster analysis results on validation data: A systematic framework. WIREs Data Mining and Knowledge Discovery, 12( 3), e1444. https://doi.org/10.1002/widm.1444
There is also some work that uses cross-validation, i.e., data set splitting, for estimating the number of clusters, although this is more sophisticated than just using a single training/test split, see, e.g.,
Wang, J. “Consistent Selection of the Number of Clusters via Crossvalidation.” Biometrika 97, no. 4 (2010): 893–904. http://www.jstor.org/stable/29777144,
Fu, W. & Perry, P. O. (2020) Estimating the Number of Clusters Using Cross-Validation, Journal of Computational and Graphical Statistics, 29:1, 162-173, DOI: 10.1080/10618600.2019.1647846
A note on terminology: In some answers you read that "clustering is not classification", but that's a somewhat inappropriate use of terminology. Clustering classifies and can therefore well be called classification, as is done in some literature. A better distinction is between supervised and unsupervised classification, the latter being clustering. | Do we need to set training set and testing set for clustering? | The sample is not normally split into training and test set in clustering, because, as said in other answers, the test set will not have "true labels" available, so you can't check predictions from th | Do we need to set training set and testing set for clustering?
The sample is not normally split into training and test set in clustering, because, as said in other answers, the test set will not have "true labels" available, so you can't check predictions from the training set on it.
There are however some uses for data set splits in cluster analysis. Particularly one may be interested in whether a clustering structure that is found on one part of the data set corresponds to what goes on in the other half. This isn't quite as easy to formalise though as in supervised classification. We have a paper on this here.
Ullmann, T., Hennig, C., & Boulesteix, A.-L. (2022). Validation of cluster analysis results on validation data: A systematic framework. WIREs Data Mining and Knowledge Discovery, 12( 3), e1444. https://doi.org/10.1002/widm.1444
There is also some work that uses cross-validation, i.e., data set splitting, for estimating the number of clusters, although this is more sophisticated than just using a single training/test split, see, e.g.,
Wang, J. “Consistent Selection of the Number of Clusters via Crossvalidation.” Biometrika 97, no. 4 (2010): 893–904. http://www.jstor.org/stable/29777144,
Fu, W. & Perry, P. O. (2020) Estimating the Number of Clusters Using Cross-Validation, Journal of Computational and Graphical Statistics, 29:1, 162-173, DOI: 10.1080/10618600.2019.1647846
A note on terminology: In some answers you read that "clustering is not classification", but that's a somewhat inappropriate use of terminology. Clustering classifies and can therefore well be called classification, as is done in some literature. A better distinction is between supervised and unsupervised classification, the latter being clustering. | Do we need to set training set and testing set for clustering?
The sample is not normally split into training and test set in clustering, because, as said in other answers, the test set will not have "true labels" available, so you can't check predictions from th |
17,460 | Is Random Forest a good option for unbalanced data Classification? [closed] | Note: This post is fairly old, and might not be correct. Use it only as a starting point, not an authoritative answer.
The random forest model is built on decision trees, and decision trees are sensitive to class imbalance. Each tree is built on a "bag", and each bag is a uniform random sample from the data (with replacement). Therefore each tree will be biased in the same direction and magnitude (on average) by class imbalance.
However, several techniques exist for mitigating imbalance in classification tasks.
Some of these are general and apply to a wide variety of situations. Search for the unbalanced-classes tag on this SE site, and the class-imbalance tag on the Data Science SE site.
In addition, random forests are amenable to at least two kinds of class weighting. The first technique is to weight the tree splitting criterion (For information on how this works, see https://datascience.stackexchange.com/a/56260/1156). The other technique is to either oversample or undersample data points during the bootstrap sampling process.
In Python, weighted tree splitting is implemented in the Scikit-learn class RandomForestClassifier, as the class_weight parameter. Weighted bootstrap sampling is implemented in the Imbalanced-learn class BalancedRandomForestClassifier. Note that the Imbalanced-learn BalancedRandomForestClassifier also supports the same class_weight parameter as the Scikit-learn RandomForestClassifier.
In R, both techniques are implemented in the Ranger, in the main ranger function, as the class.weights, case.weights, and sample.fraction parameters. See https://stats.stackexchange.com/a/287849/36229 for a usage example; there is helpful information in the other answers on that same question as well.
Apparently, in every extreme cases of class imbalance, you might need to adjust the minimum node size or other "detailed" parameters to get the model to work at all. See, e.g. https://stackoverflow.com/a/8704882/2954547. | Is Random Forest a good option for unbalanced data Classification? [closed] | Note: This post is fairly old, and might not be correct. Use it only as a starting point, not an authoritative answer.
The random forest model is built on decision trees, and decision trees are sensi | Is Random Forest a good option for unbalanced data Classification? [closed]
Note: This post is fairly old, and might not be correct. Use it only as a starting point, not an authoritative answer.
The random forest model is built on decision trees, and decision trees are sensitive to class imbalance. Each tree is built on a "bag", and each bag is a uniform random sample from the data (with replacement). Therefore each tree will be biased in the same direction and magnitude (on average) by class imbalance.
However, several techniques exist for mitigating imbalance in classification tasks.
Some of these are general and apply to a wide variety of situations. Search for the unbalanced-classes tag on this SE site, and the class-imbalance tag on the Data Science SE site.
In addition, random forests are amenable to at least two kinds of class weighting. The first technique is to weight the tree splitting criterion (For information on how this works, see https://datascience.stackexchange.com/a/56260/1156). The other technique is to either oversample or undersample data points during the bootstrap sampling process.
In Python, weighted tree splitting is implemented in the Scikit-learn class RandomForestClassifier, as the class_weight parameter. Weighted bootstrap sampling is implemented in the Imbalanced-learn class BalancedRandomForestClassifier. Note that the Imbalanced-learn BalancedRandomForestClassifier also supports the same class_weight parameter as the Scikit-learn RandomForestClassifier.
In R, both techniques are implemented in the Ranger, in the main ranger function, as the class.weights, case.weights, and sample.fraction parameters. See https://stats.stackexchange.com/a/287849/36229 for a usage example; there is helpful information in the other answers on that same question as well.
Apparently, in every extreme cases of class imbalance, you might need to adjust the minimum node size or other "detailed" parameters to get the model to work at all. See, e.g. https://stackoverflow.com/a/8704882/2954547. | Is Random Forest a good option for unbalanced data Classification? [closed]
Note: This post is fairly old, and might not be correct. Use it only as a starting point, not an authoritative answer.
The random forest model is built on decision trees, and decision trees are sensi |
17,461 | Is Random Forest a good option for unbalanced data Classification? [closed] | Unbalanced classes are only a an issue if you also have misclassification cost imbalance. If there are small minority classes and it is not more expensive to classify them as a majority class than the other way around, then the rational thing to do is to allow misclassification of minority classes.
So let's assume you have class and cost imbalance. There are multiple ways to deal with this. Max Kuhn's book "Applied predictive modeling" has a good overview in chapter 16. Those remedies include using a cutoff other than 0.5 which reflects the unequal costs. This is easy to do in binary classification as long as your classifier outputs label probabilities (trees and forests do this). I haven't looked into it for multiple classes yet. You can also oversample the minority class to give it more weight. | Is Random Forest a good option for unbalanced data Classification? [closed] | Unbalanced classes are only a an issue if you also have misclassification cost imbalance. If there are small minority classes and it is not more expensive to classify them as a majority class than the | Is Random Forest a good option for unbalanced data Classification? [closed]
Unbalanced classes are only a an issue if you also have misclassification cost imbalance. If there are small minority classes and it is not more expensive to classify them as a majority class than the other way around, then the rational thing to do is to allow misclassification of minority classes.
So let's assume you have class and cost imbalance. There are multiple ways to deal with this. Max Kuhn's book "Applied predictive modeling" has a good overview in chapter 16. Those remedies include using a cutoff other than 0.5 which reflects the unequal costs. This is easy to do in binary classification as long as your classifier outputs label probabilities (trees and forests do this). I haven't looked into it for multiple classes yet. You can also oversample the minority class to give it more weight. | Is Random Forest a good option for unbalanced data Classification? [closed]
Unbalanced classes are only a an issue if you also have misclassification cost imbalance. If there are small minority classes and it is not more expensive to classify them as a majority class than the |
17,462 | How do you keep up to date with the latest research? | As a data scientist, I need to keep up with the latest research in the computing, software and the data domains. And here are some things which I do to keep myself updated (apart from lurking in Gitxiv):
Quora: Amazing trove of information. This is a place where one can get questions answered by experts and also learn about information. So, it is a great place to keep oneself updated about the advancements in the computing and the software industries and the domain of interest.
Data and software Blogs: There are a plethora of data blogs on the internet. All of them have rich theoretical information, and some even explain real world data projects really nicely. The software blogs help me in keeping myself up-to-date about latest software practices and latest data science software too. Example
Engineering Blogs: The reason behind listing this as a separate bullet is because they are addictive. They are excellently written, and talks about the state of the art data and software practices followed at some top companies. Some of my favourite are: Buffer Airbnb and Pinterest
Bonus: This Quora question
LinkedIn groups: LinkedIn groups are a great way to ask questions and interact with some of the best in the industry. The LinkedIn pulse is also a great way to keep oneself updated with wonderful posts from top influencers.
Asking people doubts: Asking people specific and nice doubts would be very helpful and a nice way to interact with some of the best in the industry. A related example. | How do you keep up to date with the latest research? | As a data scientist, I need to keep up with the latest research in the computing, software and the data domains. And here are some things which I do to keep myself updated (apart from lurking in Gitxi | How do you keep up to date with the latest research?
As a data scientist, I need to keep up with the latest research in the computing, software and the data domains. And here are some things which I do to keep myself updated (apart from lurking in Gitxiv):
Quora: Amazing trove of information. This is a place where one can get questions answered by experts and also learn about information. So, it is a great place to keep oneself updated about the advancements in the computing and the software industries and the domain of interest.
Data and software Blogs: There are a plethora of data blogs on the internet. All of them have rich theoretical information, and some even explain real world data projects really nicely. The software blogs help me in keeping myself up-to-date about latest software practices and latest data science software too. Example
Engineering Blogs: The reason behind listing this as a separate bullet is because they are addictive. They are excellently written, and talks about the state of the art data and software practices followed at some top companies. Some of my favourite are: Buffer Airbnb and Pinterest
Bonus: This Quora question
LinkedIn groups: LinkedIn groups are a great way to ask questions and interact with some of the best in the industry. The LinkedIn pulse is also a great way to keep oneself updated with wonderful posts from top influencers.
Asking people doubts: Asking people specific and nice doubts would be very helpful and a nice way to interact with some of the best in the industry. A related example. | How do you keep up to date with the latest research?
As a data scientist, I need to keep up with the latest research in the computing, software and the data domains. And here are some things which I do to keep myself updated (apart from lurking in Gitxi |
17,463 | How do you keep up to date with the latest research? | Attending the seminar and conferences is the best way. When you talk to active researchers they'll share more background about what's going on in the field, rumors, unfiltered opinions etc.
I remember in my old days in physics, we had this group of researchers who published a lot, but those who're in the field knew that it was junk. So, if you're not going to conferences it would be hard to figure out.
UPDATE:
I also have a profile in Google Scholar and ResearchGate. Both recommend papers based on what papers you publish and read through these portals. I found that both produce a lot of noise, but Google Scholar hints to relevant interesting papers more often. I also look up almost always first in Scholar, so it knows well what kind of stuff I often look for. | How do you keep up to date with the latest research? | Attending the seminar and conferences is the best way. When you talk to active researchers they'll share more background about what's going on in the field, rumors, unfiltered opinions etc.
I remembe | How do you keep up to date with the latest research?
Attending the seminar and conferences is the best way. When you talk to active researchers they'll share more background about what's going on in the field, rumors, unfiltered opinions etc.
I remember in my old days in physics, we had this group of researchers who published a lot, but those who're in the field knew that it was junk. So, if you're not going to conferences it would be hard to figure out.
UPDATE:
I also have a profile in Google Scholar and ResearchGate. Both recommend papers based on what papers you publish and read through these portals. I found that both produce a lot of noise, but Google Scholar hints to relevant interesting papers more often. I also look up almost always first in Scholar, so it knows well what kind of stuff I often look for. | How do you keep up to date with the latest research?
Attending the seminar and conferences is the best way. When you talk to active researchers they'll share more background about what's going on in the field, rumors, unfiltered opinions etc.
I remembe |
17,464 | How do you keep up to date with the latest research? | I register for email list for the table of contents of the most reputable journals.I have registered for New England Journal of Medicine, Lancet, JAMA, BMJ, Clinical Infectious Diseases, etc | How do you keep up to date with the latest research? | I register for email list for the table of contents of the most reputable journals.I have registered for New England Journal of Medicine, Lancet, JAMA, BMJ, Clinical Infectious Diseases, etc | How do you keep up to date with the latest research?
I register for email list for the table of contents of the most reputable journals.I have registered for New England Journal of Medicine, Lancet, JAMA, BMJ, Clinical Infectious Diseases, etc | How do you keep up to date with the latest research?
I register for email list for the table of contents of the most reputable journals.I have registered for New England Journal of Medicine, Lancet, JAMA, BMJ, Clinical Infectious Diseases, etc |
17,465 | How do you keep up to date with the latest research? | The main thing you're probably looking for is a way to quickly weed out the "junk" that's not interesting to you in whatever field you're in.
Emails from journals listing their recently published papers are good, but even better is things like RSS feeds, which allow you to aggregate results in your feed reader of choice. Having the results of multiple journals in a single place allows you to rapidly sort titles into piles like "read", "don't read" and "maybe". But often there are so many journals which touch on your area of focus that even that can be unwieldy.
I'm holding out hope for machine-learning type recommendation engines that can learn what sort of papers I'm interested in and sort things automatically. Sort of like a Netflix/Amazon recommendation service, but for journal articles. There's none yet I can recommend whole-heartedly, but I've played around with Sparrho, and it seems to work decently. Another recommendation engine site I'm aware of is PubChase, but that's biomedical only. | How do you keep up to date with the latest research? | The main thing you're probably looking for is a way to quickly weed out the "junk" that's not interesting to you in whatever field you're in.
Emails from journals listing their recently published pape | How do you keep up to date with the latest research?
The main thing you're probably looking for is a way to quickly weed out the "junk" that's not interesting to you in whatever field you're in.
Emails from journals listing their recently published papers are good, but even better is things like RSS feeds, which allow you to aggregate results in your feed reader of choice. Having the results of multiple journals in a single place allows you to rapidly sort titles into piles like "read", "don't read" and "maybe". But often there are so many journals which touch on your area of focus that even that can be unwieldy.
I'm holding out hope for machine-learning type recommendation engines that can learn what sort of papers I'm interested in and sort things automatically. Sort of like a Netflix/Amazon recommendation service, but for journal articles. There's none yet I can recommend whole-heartedly, but I've played around with Sparrho, and it seems to work decently. Another recommendation engine site I'm aware of is PubChase, but that's biomedical only. | How do you keep up to date with the latest research?
The main thing you're probably looking for is a way to quickly weed out the "junk" that's not interesting to you in whatever field you're in.
Emails from journals listing their recently published pape |
17,466 | How do you keep up to date with the latest research? | Ps: Im only answering this question with the intentions of helping a mere mortal like me who takes a little long to go through a typical machine learning research paper and doesnt mind reading layman sumaries of this research papers.
To keep up to date with the latest machine learning and deep learning research, I usually go through summaries of research machine learning papers, written in layman terms from the following sources:
The morning paper.
ShortScience.org - Making Science Accessible
Again: this is what I do to keep up to date with the latest research as I tend to take long to go through a typical research paper. | How do you keep up to date with the latest research? | Ps: Im only answering this question with the intentions of helping a mere mortal like me who takes a little long to go through a typical machine learning research paper and doesnt mind reading layman | How do you keep up to date with the latest research?
Ps: Im only answering this question with the intentions of helping a mere mortal like me who takes a little long to go through a typical machine learning research paper and doesnt mind reading layman sumaries of this research papers.
To keep up to date with the latest machine learning and deep learning research, I usually go through summaries of research machine learning papers, written in layman terms from the following sources:
The morning paper.
ShortScience.org - Making Science Accessible
Again: this is what I do to keep up to date with the latest research as I tend to take long to go through a typical research paper. | How do you keep up to date with the latest research?
Ps: Im only answering this question with the intentions of helping a mere mortal like me who takes a little long to go through a typical machine learning research paper and doesnt mind reading layman |
17,467 | Other unbiased estimators than the BLUE (OLS solution) for linear models | One example that comes to mind is some GLS estimator that weights observations differently although that is not necessary when the Gauss-Markov assumptions are met (which the statistician may not know to be the case and hence apply still apply GLS).
Consider the case of a regression of $y_i$, $i=1,\ldots,n$ on a constant for illustration (readily generalizes to general GLS estimators). Here, $\{y_i\}$ is assumed to be a random sample from a population with mean $\mu$ and variance $\sigma^2$.
Then, we know that OLS is just $\hat\beta=\bar y$, the sample mean. To emphasize the point that each observation is weighted with weight $1/n$, write this as
$$
\hat\beta=\sum_{i=1}^n\frac{1}{n}y_i.
$$
It is well-known that $Var(\hat\beta)=\sigma^2/n$.
Now, consider another estimator which can be written as
$$
\tilde\beta=\sum_{i=1}^nw_iy_i,
$$
where the weights are such that $\sum_iw_i=1$. This ensures that the estimator is unbiased, as
$$
E\left(\sum_{i=1}^nw_iy_i\right)=\sum_{i=1}^nw_iE(y_i)=\sum_{i=1}^nw_i\mu=\mu.
$$
Its variance will exceed that of OLS unless $w_i=1/n$ for all $i$ (in which case it will of course reduce to OLS), which can for instance be shown via a Lagrangian:
\begin{align*}
L&=V(\tilde\beta)-\lambda\left(\sum_iw_i-1\right)\\
&=\sum_iw_i^2\sigma^2-\lambda\left(\sum_iw_i-1\right),
\end{align*}
with partial derivatives w.r.t. $w_i$ set to zero being equal to $2\sigma^2w_i-\lambda=0$ for all $i$, and $\partial L/\partial\lambda=0$ equaling $\sum_iw_i-1=0$. Solving the first set of derivatives for $\lambda$ and equating them yields $w_i=w_j$, which implies $w_i=1/n$ minimizes the variance, by the requirement that the weights sum to one.
Here is a graphical illustration from a little simulation, created with the code below:
EDIT: In response to @kjetilbhalvorsen's and @RichardHardy's suggestions I also include the median of the $y_i$, the MLE of the location parameter pf a t(4) distribution (I get warnings that In log(s) : NaNs produced that I did not check further) and Huber's estimator in the plot.
We observe that all estimators seem to be unbiased. However, the estimator that uses weights $w_i=(1\pm\epsilon)/n$ as weights for either half of the sample is more variable, as are the median, the MLE of the t-distribution and Huber's estimator (the latter only slightly so, see also here).
That the latter three are outperformed by the OLS solution is not immediately implied by the BLUE property (at least not to me), as it is not obvious if they are linear estimators (nor do I know if the MLE and Huber are unbiased).
library(MASS)
n <- 100
reps <- 1e6
epsilon <- 0.5
w <- c(rep((1+epsilon)/n,n/2),rep((1-epsilon)/n,n/2))
ols <- weightedestimator <- lad <- mle.t4 <- huberest <- rep(NA,reps)
for (i in 1:reps)
{
y <- rnorm(n)
ols[i] <- mean(y)
weightedestimator[i] <- crossprod(w,y)
lad[i] <- median(y)
mle.t4[i] <- fitdistr(y, "t", df=4)$estimate[1]
huberest[i] <- huber(y)$mu
}
plot(density(ols), col="purple", lwd=3, main="Kernel-estimate of density of OLS and other estimators",xlab="")
lines(density(weightedestimator), col="lightblue2", lwd=3)
lines(density(lad), col="salmon", lwd=3)
lines(density(mle.t4), col="green", lwd=3)
lines(density(huberest), col="#949413", lwd=3)
abline(v=0,lty=2)
legend('topright', c("OLS","weighted","median", "MLE t, 4 df", "Huber"), col=c("purple","lightblue","salmon","green", "#949413"), lwd=3) | Other unbiased estimators than the BLUE (OLS solution) for linear models | One example that comes to mind is some GLS estimator that weights observations differently although that is not necessary when the Gauss-Markov assumptions are met (which the statistician may not know | Other unbiased estimators than the BLUE (OLS solution) for linear models
One example that comes to mind is some GLS estimator that weights observations differently although that is not necessary when the Gauss-Markov assumptions are met (which the statistician may not know to be the case and hence apply still apply GLS).
Consider the case of a regression of $y_i$, $i=1,\ldots,n$ on a constant for illustration (readily generalizes to general GLS estimators). Here, $\{y_i\}$ is assumed to be a random sample from a population with mean $\mu$ and variance $\sigma^2$.
Then, we know that OLS is just $\hat\beta=\bar y$, the sample mean. To emphasize the point that each observation is weighted with weight $1/n$, write this as
$$
\hat\beta=\sum_{i=1}^n\frac{1}{n}y_i.
$$
It is well-known that $Var(\hat\beta)=\sigma^2/n$.
Now, consider another estimator which can be written as
$$
\tilde\beta=\sum_{i=1}^nw_iy_i,
$$
where the weights are such that $\sum_iw_i=1$. This ensures that the estimator is unbiased, as
$$
E\left(\sum_{i=1}^nw_iy_i\right)=\sum_{i=1}^nw_iE(y_i)=\sum_{i=1}^nw_i\mu=\mu.
$$
Its variance will exceed that of OLS unless $w_i=1/n$ for all $i$ (in which case it will of course reduce to OLS), which can for instance be shown via a Lagrangian:
\begin{align*}
L&=V(\tilde\beta)-\lambda\left(\sum_iw_i-1\right)\\
&=\sum_iw_i^2\sigma^2-\lambda\left(\sum_iw_i-1\right),
\end{align*}
with partial derivatives w.r.t. $w_i$ set to zero being equal to $2\sigma^2w_i-\lambda=0$ for all $i$, and $\partial L/\partial\lambda=0$ equaling $\sum_iw_i-1=0$. Solving the first set of derivatives for $\lambda$ and equating them yields $w_i=w_j$, which implies $w_i=1/n$ minimizes the variance, by the requirement that the weights sum to one.
Here is a graphical illustration from a little simulation, created with the code below:
EDIT: In response to @kjetilbhalvorsen's and @RichardHardy's suggestions I also include the median of the $y_i$, the MLE of the location parameter pf a t(4) distribution (I get warnings that In log(s) : NaNs produced that I did not check further) and Huber's estimator in the plot.
We observe that all estimators seem to be unbiased. However, the estimator that uses weights $w_i=(1\pm\epsilon)/n$ as weights for either half of the sample is more variable, as are the median, the MLE of the t-distribution and Huber's estimator (the latter only slightly so, see also here).
That the latter three are outperformed by the OLS solution is not immediately implied by the BLUE property (at least not to me), as it is not obvious if they are linear estimators (nor do I know if the MLE and Huber are unbiased).
library(MASS)
n <- 100
reps <- 1e6
epsilon <- 0.5
w <- c(rep((1+epsilon)/n,n/2),rep((1-epsilon)/n,n/2))
ols <- weightedestimator <- lad <- mle.t4 <- huberest <- rep(NA,reps)
for (i in 1:reps)
{
y <- rnorm(n)
ols[i] <- mean(y)
weightedestimator[i] <- crossprod(w,y)
lad[i] <- median(y)
mle.t4[i] <- fitdistr(y, "t", df=4)$estimate[1]
huberest[i] <- huber(y)$mu
}
plot(density(ols), col="purple", lwd=3, main="Kernel-estimate of density of OLS and other estimators",xlab="")
lines(density(weightedestimator), col="lightblue2", lwd=3)
lines(density(lad), col="salmon", lwd=3)
lines(density(mle.t4), col="green", lwd=3)
lines(density(huberest), col="#949413", lwd=3)
abline(v=0,lty=2)
legend('topright', c("OLS","weighted","median", "MLE t, 4 df", "Huber"), col=c("purple","lightblue","salmon","green", "#949413"), lwd=3) | Other unbiased estimators than the BLUE (OLS solution) for linear models
One example that comes to mind is some GLS estimator that weights observations differently although that is not necessary when the Gauss-Markov assumptions are met (which the statistician may not know |
17,468 | How does "Fundamental Theorem of Factor Analysis" apply to PCA, or how are PCA loadings defined? | This is a reasonable question (+1) that stems from the terminological ambiguity and confusion.
In the context of PCA, people often call principal axes (eigenvectors of the covariance/correlation matrix) "loadings". This is sloppy terminology. What should rather be called "loadings" in PCA, are principal axes scaled by the square roots of the respective eigenvalues. Then the theorem you are referring to will hold.
Indeed, if the eigen-decomposition of the correlation matrix is $$\mathbf R = \mathbf V \mathbf S \mathbf V^\top$$ where $\mathbf V$ are eigenvectors (principal axes) and $\mathbf S$ is a diagonal matrix of eigenvalues, and if we define loadings as $$\mathbf A = \mathbf V \mathbf S^{1/2},$$ then one can easily see that $$\mathbf R = \mathbf A \mathbf A^\top.$$ Moreover, the best rank-$r$ approximation to the correlation matrix is given by the first $r$ PCA loadings: $$\mathbf R \approx \mathbf A_r \mathbf A_r^\top.$$
Please see my answer here for more about reconstructing covariance matrices with factor analysis and PCA loadings. | How does "Fundamental Theorem of Factor Analysis" apply to PCA, or how are PCA loadings defined? | This is a reasonable question (+1) that stems from the terminological ambiguity and confusion.
In the context of PCA, people often call principal axes (eigenvectors of the covariance/correlation matri | How does "Fundamental Theorem of Factor Analysis" apply to PCA, or how are PCA loadings defined?
This is a reasonable question (+1) that stems from the terminological ambiguity and confusion.
In the context of PCA, people often call principal axes (eigenvectors of the covariance/correlation matrix) "loadings". This is sloppy terminology. What should rather be called "loadings" in PCA, are principal axes scaled by the square roots of the respective eigenvalues. Then the theorem you are referring to will hold.
Indeed, if the eigen-decomposition of the correlation matrix is $$\mathbf R = \mathbf V \mathbf S \mathbf V^\top$$ where $\mathbf V$ are eigenvectors (principal axes) and $\mathbf S$ is a diagonal matrix of eigenvalues, and if we define loadings as $$\mathbf A = \mathbf V \mathbf S^{1/2},$$ then one can easily see that $$\mathbf R = \mathbf A \mathbf A^\top.$$ Moreover, the best rank-$r$ approximation to the correlation matrix is given by the first $r$ PCA loadings: $$\mathbf R \approx \mathbf A_r \mathbf A_r^\top.$$
Please see my answer here for more about reconstructing covariance matrices with factor analysis and PCA loadings. | How does "Fundamental Theorem of Factor Analysis" apply to PCA, or how are PCA loadings defined?
This is a reasonable question (+1) that stems from the terminological ambiguity and confusion.
In the context of PCA, people often call principal axes (eigenvectors of the covariance/correlation matri |
17,469 | "Dummy variable" versus "indicator variable" for nominal/categorical data | I'd say "dummy variable" is a more general way to refer to (one of) the numerical variable(s) that represents (together represent) a categorical predictor; therefore the term applies also to those used in Helmert & effect coding†. That's mainly owing to the general use of "dummy" to mean "stand-in". "Indicator variable" I relate to indicator functions‡—so those can only be one or zero to indicate having or not having some property; therefore the term applies only to those used in reference-level coding※. Of course some people use "dummy coding" to mean "reference-level coding"; they presumably have a more restricted definition of "dummy variables", or at any rate ought to have.
† And if you don't call those "dummies", what do you call them?
‡ So e.g. the dummy $x_i$ is an indicator variable for when the $i$th person $u_i$ is male (a member of set $M$):
$$
x_i=\boldsymbol{1}_\mathrm{M}(u_i)=\left\{
\begin{array}{l l}
1 & \mathrm{when}\ u_i \in M\\
0 & \mathrm{when}\ u_i \notin M\\
\end{array}\right.$$
where $\boldsymbol{1}_M(\cdot)$ is the indicator function for membership of $M$.
※ Or, as @gung has pointed out, level-means coding. | "Dummy variable" versus "indicator variable" for nominal/categorical data | I'd say "dummy variable" is a more general way to refer to (one of) the numerical variable(s) that represents (together represent) a categorical predictor; therefore the term applies also to those use | "Dummy variable" versus "indicator variable" for nominal/categorical data
I'd say "dummy variable" is a more general way to refer to (one of) the numerical variable(s) that represents (together represent) a categorical predictor; therefore the term applies also to those used in Helmert & effect coding†. That's mainly owing to the general use of "dummy" to mean "stand-in". "Indicator variable" I relate to indicator functions‡—so those can only be one or zero to indicate having or not having some property; therefore the term applies only to those used in reference-level coding※. Of course some people use "dummy coding" to mean "reference-level coding"; they presumably have a more restricted definition of "dummy variables", or at any rate ought to have.
† And if you don't call those "dummies", what do you call them?
‡ So e.g. the dummy $x_i$ is an indicator variable for when the $i$th person $u_i$ is male (a member of set $M$):
$$
x_i=\boldsymbol{1}_\mathrm{M}(u_i)=\left\{
\begin{array}{l l}
1 & \mathrm{when}\ u_i \in M\\
0 & \mathrm{when}\ u_i \notin M\\
\end{array}\right.$$
where $\boldsymbol{1}_M(\cdot)$ is the indicator function for membership of $M$.
※ Or, as @gung has pointed out, level-means coding. | "Dummy variable" versus "indicator variable" for nominal/categorical data
I'd say "dummy variable" is a more general way to refer to (one of) the numerical variable(s) that represents (together represent) a categorical predictor; therefore the term applies also to those use |
17,470 | "Dummy variable" versus "indicator variable" for nominal/categorical data | @Scortchi has provided a good answer here. Let me add one small point. Even using the stricter definition of indicator variable, this can still be associated with (at least) two different coding schemes for categorical data in a regression-type model: viz. reference level coding and level means coding. With level means coding, you have a categorical variable with $k$ levels that are represented with $k$ indicator variables, but you do not include a vector of $1$s for the intercept (i.e., the intercept is suppressed). (For a fuller explication, with example model matrices, see my answer here: How can logistic regression have a factorial predictor and no intercept?) When there is only a single categorical variable, this yields model output in a way that is simple and may be preferred by some people. (For an example where using this scheme facilitates comparisons of interest, see my answer here: Why do the estimated values from a Best Linear Unbiased Predictor (BLUP) differ from a Best Linear Unbiased Estimator (BLUE)?) | "Dummy variable" versus "indicator variable" for nominal/categorical data | @Scortchi has provided a good answer here. Let me add one small point. Even using the stricter definition of indicator variable, this can still be associated with (at least) two different coding sch | "Dummy variable" versus "indicator variable" for nominal/categorical data
@Scortchi has provided a good answer here. Let me add one small point. Even using the stricter definition of indicator variable, this can still be associated with (at least) two different coding schemes for categorical data in a regression-type model: viz. reference level coding and level means coding. With level means coding, you have a categorical variable with $k$ levels that are represented with $k$ indicator variables, but you do not include a vector of $1$s for the intercept (i.e., the intercept is suppressed). (For a fuller explication, with example model matrices, see my answer here: How can logistic regression have a factorial predictor and no intercept?) When there is only a single categorical variable, this yields model output in a way that is simple and may be preferred by some people. (For an example where using this scheme facilitates comparisons of interest, see my answer here: Why do the estimated values from a Best Linear Unbiased Predictor (BLUP) differ from a Best Linear Unbiased Estimator (BLUE)?) | "Dummy variable" versus "indicator variable" for nominal/categorical data
@Scortchi has provided a good answer here. Let me add one small point. Even using the stricter definition of indicator variable, this can still be associated with (at least) two different coding sch |
17,471 | Standard Deviation of an Exponentially-weighted Mean | You can use the following recurrent formula:
$\sigma_i^2 = S_i = (1 - \alpha) (S_{i-1} + \alpha (x_i - \mu_{i-1})^2)$
Here $x_i$ is your observation in the $i$-th step, $\mu_{i-1}$ is the estimated EWM, and $S_{i-1}$ is the previous estimate of the variance. See Section 9 here for the proof and pseudo-code. | Standard Deviation of an Exponentially-weighted Mean | You can use the following recurrent formula:
$\sigma_i^2 = S_i = (1 - \alpha) (S_{i-1} + \alpha (x_i - \mu_{i-1})^2)$
Here $x_i$ is your observation in the $i$-th step, $\mu_{i-1}$ is the estimated EW | Standard Deviation of an Exponentially-weighted Mean
You can use the following recurrent formula:
$\sigma_i^2 = S_i = (1 - \alpha) (S_{i-1} + \alpha (x_i - \mu_{i-1})^2)$
Here $x_i$ is your observation in the $i$-th step, $\mu_{i-1}$ is the estimated EWM, and $S_{i-1}$ is the previous estimate of the variance. See Section 9 here for the proof and pseudo-code. | Standard Deviation of an Exponentially-weighted Mean
You can use the following recurrent formula:
$\sigma_i^2 = S_i = (1 - \alpha) (S_{i-1} + \alpha (x_i - \mu_{i-1})^2)$
Here $x_i$ is your observation in the $i$-th step, $\mu_{i-1}$ is the estimated EW |
17,472 | k-means vs k-median? | k-means minimizes within-cluster variance, which equals squared Euclidean distances.
In general, the arithmetic mean does this. It does not optimize distances, but squared deviations from the mean.
k-medians minimizes absolute deviations, which equals Manhattan distance.
In general, the per-axis median should do this. It is a good estimator for the mean, if you want to minimize the sum of absolute deviations (that is sum_i abs(x_i-y_i)), instead of the squared ones.
It's not a question about accuracy. It's a question of correctness. ;-)
So here's your decision tree:
If your distance is squared Euclidean distance, use k-means
If your distance is Taxicab metric, use k-medians
If you have any other distance, use k-medoids
Some exceptions: as far as I can tell, maximizing cosine similarity is related to minimizing squared Euclidean distance on L2-normalized data. So if your data is L2 normalized; and you l2-normalize your means each iteration, then you can use k-means again. | k-means vs k-median? | k-means minimizes within-cluster variance, which equals squared Euclidean distances.
In general, the arithmetic mean does this. It does not optimize distances, but squared deviations from the mean.
k- | k-means vs k-median?
k-means minimizes within-cluster variance, which equals squared Euclidean distances.
In general, the arithmetic mean does this. It does not optimize distances, but squared deviations from the mean.
k-medians minimizes absolute deviations, which equals Manhattan distance.
In general, the per-axis median should do this. It is a good estimator for the mean, if you want to minimize the sum of absolute deviations (that is sum_i abs(x_i-y_i)), instead of the squared ones.
It's not a question about accuracy. It's a question of correctness. ;-)
So here's your decision tree:
If your distance is squared Euclidean distance, use k-means
If your distance is Taxicab metric, use k-medians
If you have any other distance, use k-medoids
Some exceptions: as far as I can tell, maximizing cosine similarity is related to minimizing squared Euclidean distance on L2-normalized data. So if your data is L2 normalized; and you l2-normalize your means each iteration, then you can use k-means again. | k-means vs k-median?
k-means minimizes within-cluster variance, which equals squared Euclidean distances.
In general, the arithmetic mean does this. It does not optimize distances, but squared deviations from the mean.
k- |
17,473 | k-means vs k-median? | If you want to make an analysis not regarding of the possible effect of extreme values use k means but if you want to be more accurate use k median | k-means vs k-median? | If you want to make an analysis not regarding of the possible effect of extreme values use k means but if you want to be more accurate use k median | k-means vs k-median?
If you want to make an analysis not regarding of the possible effect of extreme values use k means but if you want to be more accurate use k median | k-means vs k-median?
If you want to make an analysis not regarding of the possible effect of extreme values use k means but if you want to be more accurate use k median |
17,474 | Weighting more recent data in Random Forest model | The ranger package in R (pdf), which is relatively new, will do this. The ranger implementation of random forests has a case.weights argument that takes a vector with individual case / observation weights. | Weighting more recent data in Random Forest model | The ranger package in R (pdf), which is relatively new, will do this. The ranger implementation of random forests has a case.weights argument that takes a vector with individual case / observation wei | Weighting more recent data in Random Forest model
The ranger package in R (pdf), which is relatively new, will do this. The ranger implementation of random forests has a case.weights argument that takes a vector with individual case / observation weights. | Weighting more recent data in Random Forest model
The ranger package in R (pdf), which is relatively new, will do this. The ranger implementation of random forests has a case.weights argument that takes a vector with individual case / observation wei |
17,475 | Weighting more recent data in Random Forest model | You could resample the data to over represent the more recent data points. Rf involves a sampel-with-replacment step anyways and "roughly balanced bagging" for unbalanced classes uses sampling to overrepresent the minority class and produces results as good or better then class weighted random forest in my experience.
You could resample at the level of constructing your training matrix (reference) instead of during bagging to keep implementation easy though I would suggest doing many repeats in that case.
Internally some implementations of random forest including scikit-learn actually use sample weights to keep track of how many times each sample is in bag and it should be equivalent to oversampling at the bagging level and close to oversampling at the training level in cross validation. | Weighting more recent data in Random Forest model | You could resample the data to over represent the more recent data points. Rf involves a sampel-with-replacment step anyways and "roughly balanced bagging" for unbalanced classes uses sampling to over | Weighting more recent data in Random Forest model
You could resample the data to over represent the more recent data points. Rf involves a sampel-with-replacment step anyways and "roughly balanced bagging" for unbalanced classes uses sampling to overrepresent the minority class and produces results as good or better then class weighted random forest in my experience.
You could resample at the level of constructing your training matrix (reference) instead of during bagging to keep implementation easy though I would suggest doing many repeats in that case.
Internally some implementations of random forest including scikit-learn actually use sample weights to keep track of how many times each sample is in bag and it should be equivalent to oversampling at the bagging level and close to oversampling at the training level in cross validation. | Weighting more recent data in Random Forest model
You could resample the data to over represent the more recent data points. Rf involves a sampel-with-replacment step anyways and "roughly balanced bagging" for unbalanced classes uses sampling to over |
17,476 | Weighting more recent data in Random Forest model | You should look into the "classwt" parameter. This doesn't seem to be what you are directly interested in, but it might give you a sense of what you want to do.
See here: Stack Exchange question #1
And here: Stack Exchange question #2
Article on weighted random forests: PDF
The basic idea is to weight classes such that rarely observed groups/classifications are more likely to be selected in your bootstrap samples. This is helpful for imbalanced data (when the prior probabilities of different classes are widely different).
It seems to me that you want to do something similar, but for recent events (not for certain groups/classifications). A simple way to do this would be to create duplicate observations (i.e. put in repeated, identical rows) for more recent observations. However, this could potentially be inefficient. I do not know of a way to directly weight each observation in R, but I could be unaware of it.
You could try looking around for alternative implementations, e.g. in C -- at worst, these could be customized with a bit of coding. | Weighting more recent data in Random Forest model | You should look into the "classwt" parameter. This doesn't seem to be what you are directly interested in, but it might give you a sense of what you want to do.
See here: Stack Exchange question #1
An | Weighting more recent data in Random Forest model
You should look into the "classwt" parameter. This doesn't seem to be what you are directly interested in, but it might give you a sense of what you want to do.
See here: Stack Exchange question #1
And here: Stack Exchange question #2
Article on weighted random forests: PDF
The basic idea is to weight classes such that rarely observed groups/classifications are more likely to be selected in your bootstrap samples. This is helpful for imbalanced data (when the prior probabilities of different classes are widely different).
It seems to me that you want to do something similar, but for recent events (not for certain groups/classifications). A simple way to do this would be to create duplicate observations (i.e. put in repeated, identical rows) for more recent observations. However, this could potentially be inefficient. I do not know of a way to directly weight each observation in R, but I could be unaware of it.
You could try looking around for alternative implementations, e.g. in C -- at worst, these could be customized with a bit of coding. | Weighting more recent data in Random Forest model
You should look into the "classwt" parameter. This doesn't seem to be what you are directly interested in, but it might give you a sense of what you want to do.
See here: Stack Exchange question #1
An |
17,477 | Bias of maximum likelihood estimators for logistic regression | Consider the simple binary logistic regression model, with a binary dependent variable and only a constant and a binary regressor $T$.
$$\Pr(Y_i=1\mid T_i=1) = \Lambda (\alpha + \beta T_i)$$
where $\Lambda$ is the logistic cdf, $\Lambda(u) = \left[1+\exp\{-u\}\right]^{-1}$.
In logit form we have
$$\ln \left(\frac{\Pr(Y_i=1\mid T_i=1)}{1-\Pr(Y_i=1\mid T_i=1)}\right) = \alpha + \beta T_i$$
You have a sample of size $n$. Denote $n_1$ the number of observations where $T_i=1$ and $n_0$ those where $T_i=0$, and $n_1+n_0=n$. Consider the following estimated conditional probabilities:
$$\hat \Pr(Y=1\mid T=1)\equiv \hat P_{1|1} = \frac 1{n_1}\sum_{T_i=1}y_i$$
$$\hat \Pr(Y=1\mid T=0)\equiv \hat P_{1|0} = \frac 1{n_0}\sum_{T_i=0}y_i$$
Then this very basic model provides closed form solutions for the ML estimator:
$$\hat \alpha = \ln\left(\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right),\qquad \hat \beta = \ln\left(\frac{\hat P_{1|1}}{1-\hat P_{1|1}}\right)-\ln\left(\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right)$$
BIAS
Although $\hat P_{1|1}$ and $\hat P_{1|0}$ are unbiased estimators of the corresponding probabilities, the MLEs are biased, since the non-linear logarithmic function gets in the way -imagine what happens to more complicated models, with a higher degree of non-linearity.
But asymptotically, the bias vanishes since the probability estimates are consistent. Inserting directly the $\lim$ operator inside the expected value and the logarithm, we have
$$\lim_{n\rightarrow \infty}E[\hat \alpha] = E\left[\ln\left(\lim_{n\rightarrow \infty}\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right)\right] = E\left[\ln\left(\frac{P_{1|0}}{1-P_{1|0}}\right)\right] =\alpha$$
and likewise for $\beta$.
VARIANCE-COVARIANCE MATRIX OF MLE
In the above simple case that provides closed-form expressions for the estimator, one could, at least in principle, go on and derive its exact finite-sample distribution and then calculate its exact finite sample variance-covariance matrix. But in general, the MLE has no closed form solution. Then we resort to a consistent estimate of the asymptotic variance-covariance matrix, which is indeed (the negative of) the inverse of the Hessian of the log-likelihood function of the sample, evaluated at the MLE. And there is no "arbitrary choice" here at all, but it results from asymptotic theory and the asymptotic properties of the MLE (consistency and asymptotic normality), that tells us that, for $\theta_0 = (\alpha, \beta)$,
$${\sqrt n}(\hat \theta-\theta_0)\rightarrow_d N\left(0, -(E[H])^{-1}\right)$$
where $H$ is the Hessian. Approximately and for (large) finite samples, this leads us to
$$\operatorname{Var}(\hat \theta) \approx -\frac 1n(E[H])^{-1}\approx -\frac 1n\left(\frac 1n\hat H\right)^{-1}=-\hat H^{-1}$$ | Bias of maximum likelihood estimators for logistic regression | Consider the simple binary logistic regression model, with a binary dependent variable and only a constant and a binary regressor $T$.
$$\Pr(Y_i=1\mid T_i=1) = \Lambda (\alpha + \beta T_i)$$
where $\L | Bias of maximum likelihood estimators for logistic regression
Consider the simple binary logistic regression model, with a binary dependent variable and only a constant and a binary regressor $T$.
$$\Pr(Y_i=1\mid T_i=1) = \Lambda (\alpha + \beta T_i)$$
where $\Lambda$ is the logistic cdf, $\Lambda(u) = \left[1+\exp\{-u\}\right]^{-1}$.
In logit form we have
$$\ln \left(\frac{\Pr(Y_i=1\mid T_i=1)}{1-\Pr(Y_i=1\mid T_i=1)}\right) = \alpha + \beta T_i$$
You have a sample of size $n$. Denote $n_1$ the number of observations where $T_i=1$ and $n_0$ those where $T_i=0$, and $n_1+n_0=n$. Consider the following estimated conditional probabilities:
$$\hat \Pr(Y=1\mid T=1)\equiv \hat P_{1|1} = \frac 1{n_1}\sum_{T_i=1}y_i$$
$$\hat \Pr(Y=1\mid T=0)\equiv \hat P_{1|0} = \frac 1{n_0}\sum_{T_i=0}y_i$$
Then this very basic model provides closed form solutions for the ML estimator:
$$\hat \alpha = \ln\left(\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right),\qquad \hat \beta = \ln\left(\frac{\hat P_{1|1}}{1-\hat P_{1|1}}\right)-\ln\left(\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right)$$
BIAS
Although $\hat P_{1|1}$ and $\hat P_{1|0}$ are unbiased estimators of the corresponding probabilities, the MLEs are biased, since the non-linear logarithmic function gets in the way -imagine what happens to more complicated models, with a higher degree of non-linearity.
But asymptotically, the bias vanishes since the probability estimates are consistent. Inserting directly the $\lim$ operator inside the expected value and the logarithm, we have
$$\lim_{n\rightarrow \infty}E[\hat \alpha] = E\left[\ln\left(\lim_{n\rightarrow \infty}\frac{\hat P_{1|0}}{1-\hat P_{1|0}}\right)\right] = E\left[\ln\left(\frac{P_{1|0}}{1-P_{1|0}}\right)\right] =\alpha$$
and likewise for $\beta$.
VARIANCE-COVARIANCE MATRIX OF MLE
In the above simple case that provides closed-form expressions for the estimator, one could, at least in principle, go on and derive its exact finite-sample distribution and then calculate its exact finite sample variance-covariance matrix. But in general, the MLE has no closed form solution. Then we resort to a consistent estimate of the asymptotic variance-covariance matrix, which is indeed (the negative of) the inverse of the Hessian of the log-likelihood function of the sample, evaluated at the MLE. And there is no "arbitrary choice" here at all, but it results from asymptotic theory and the asymptotic properties of the MLE (consistency and asymptotic normality), that tells us that, for $\theta_0 = (\alpha, \beta)$,
$${\sqrt n}(\hat \theta-\theta_0)\rightarrow_d N\left(0, -(E[H])^{-1}\right)$$
where $H$ is the Hessian. Approximately and for (large) finite samples, this leads us to
$$\operatorname{Var}(\hat \theta) \approx -\frac 1n(E[H])^{-1}\approx -\frac 1n\left(\frac 1n\hat H\right)^{-1}=-\hat H^{-1}$$ | Bias of maximum likelihood estimators for logistic regression
Consider the simple binary logistic regression model, with a binary dependent variable and only a constant and a binary regressor $T$.
$$\Pr(Y_i=1\mid T_i=1) = \Lambda (\alpha + \beta T_i)$$
where $\L |
17,478 | Prediction on mixed effect models: what to do with random effects? | If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at. The default is the highest or innermost which means that if you don't specify the level then it is trying to predict at the subject level. If you specify level=0 as part of your first predict call (without subject) then it will give the prediction at the population level and not need a subject number. | Prediction on mixed effect models: what to do with random effects? | If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at. The default is the highest or innermost which means that if y | Prediction on mixed effect models: what to do with random effects?
If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at. The default is the highest or innermost which means that if you don't specify the level then it is trying to predict at the subject level. If you specify level=0 as part of your first predict call (without subject) then it will give the prediction at the population level and not need a subject number. | Prediction on mixed effect models: what to do with random effects?
If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at. The default is the highest or innermost which means that if y |
17,479 | How to find variance between multidimensional points? | For a $p$-dimensional random variable $X = {\left( {{X_1}, \ldots ,{X_p}} \right)^\intercal}$, we have the following definition of the variance:
$$Var\left( X \right) = E\left[ {\left( {X - EX} \right){{\left( {X - EX} \right)}^\intercal}} \right] = \left( {\begin{array}{*{20}{c}}
{Var\left( {{X_1}} \right)}& \ldots &{Cov\left( {{X_1},{X_p}} \right)} \\
\vdots & \ddots & \vdots \\
{Cov\left( {{X_p},{X_1}} \right)}& \ldots &{Var\left( {{X_p}} \right)}
\end{array}} \right)$$
That is, the variance of a random vector is defined as the matrix which stores all the variances on the main diagonal and the covariances between the different components in the other elements. The sample $p \times p$ covariance matrix would then be calculated by plugging in the sample analogs for the population variables:
$$\frac{1}{{n - 1}}\left( {\begin{array}{*{20}{c}}
{\sum\limits_{i = 1}^n {{{\left( {{X_{i1}} - {{\bar X}_{\cdot1}}} \right)}^2}} }& \ldots &{\sum\limits_{i = 1}^n {\left( {{X_{i1}} - {{\bar X}_{\cdot1}}} \right)\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)} } \\
\vdots & \ddots & \vdots \\
{\sum\limits_{i = 1}^n {\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)\left( {{X_{i1}} - {{\bar X}_{\cdot 1}}} \right)} }& \ldots &{\sum\limits_{i = 1}^n {{{\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)}^2}} }
\end{array}} \right)$$
where ${X_{ij}}$ denotes the $i$th observation for feature $j$ and ${{\bar X}_{ \cdot j}}$ the sample mean of the $j$th feature. To sum up, the variance of a random vector is defined as the matrix containing the individual variances and covariances. It therefore suffices to calculate the sample variances and covariances for all the vector components individually. | How to find variance between multidimensional points? | For a $p$-dimensional random variable $X = {\left( {{X_1}, \ldots ,{X_p}} \right)^\intercal}$, we have the following definition of the variance:
$$Var\left( X \right) = E\left[ {\left( {X - EX} \righ | How to find variance between multidimensional points?
For a $p$-dimensional random variable $X = {\left( {{X_1}, \ldots ,{X_p}} \right)^\intercal}$, we have the following definition of the variance:
$$Var\left( X \right) = E\left[ {\left( {X - EX} \right){{\left( {X - EX} \right)}^\intercal}} \right] = \left( {\begin{array}{*{20}{c}}
{Var\left( {{X_1}} \right)}& \ldots &{Cov\left( {{X_1},{X_p}} \right)} \\
\vdots & \ddots & \vdots \\
{Cov\left( {{X_p},{X_1}} \right)}& \ldots &{Var\left( {{X_p}} \right)}
\end{array}} \right)$$
That is, the variance of a random vector is defined as the matrix which stores all the variances on the main diagonal and the covariances between the different components in the other elements. The sample $p \times p$ covariance matrix would then be calculated by plugging in the sample analogs for the population variables:
$$\frac{1}{{n - 1}}\left( {\begin{array}{*{20}{c}}
{\sum\limits_{i = 1}^n {{{\left( {{X_{i1}} - {{\bar X}_{\cdot1}}} \right)}^2}} }& \ldots &{\sum\limits_{i = 1}^n {\left( {{X_{i1}} - {{\bar X}_{\cdot1}}} \right)\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)} } \\
\vdots & \ddots & \vdots \\
{\sum\limits_{i = 1}^n {\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)\left( {{X_{i1}} - {{\bar X}_{\cdot 1}}} \right)} }& \ldots &{\sum\limits_{i = 1}^n {{{\left( {{X_{ip}} - {{\bar X}_{\cdot p}}} \right)}^2}} }
\end{array}} \right)$$
where ${X_{ij}}$ denotes the $i$th observation for feature $j$ and ${{\bar X}_{ \cdot j}}$ the sample mean of the $j$th feature. To sum up, the variance of a random vector is defined as the matrix containing the individual variances and covariances. It therefore suffices to calculate the sample variances and covariances for all the vector components individually. | How to find variance between multidimensional points?
For a $p$-dimensional random variable $X = {\left( {{X_1}, \ldots ,{X_p}} \right)^\intercal}$, we have the following definition of the variance:
$$Var\left( X \right) = E\left[ {\left( {X - EX} \righ |
17,480 | Poisson is to exponential as Gamma-Poisson is to what? | This is a fairly straight forward problem. Although there is a connection between the Poisson and Negative Binomial distributions, I actually think this is unhelpful for your specific question as it encourages people to think of negative binomial processes. Basically, you have a series of Poisson processes:
$$Y_i(t_i)|\lambda_i\sim Poisson(\lambda_i t_i)$$
Where $Y_i$ is the process and $t_i$ is the time you observe it, and $i$ denotes the individuals. And you are saying that these processes are "similar" by tying the rates together by a distribution:
$$\lambda_i\sim Gamma(\alpha,\beta)$$
On doing the integration/mxixing over $\lambda_i$, you have:
$$Y_i(t_i)|\alpha\beta\sim NegBin(\alpha,p_i)\;\;\; where \;\;p_i=\frac{t_i}{t_i+\beta}$$
This has a pmf of:
$$Pr(Y_i(t_i)=y_i|\alpha\beta) = \frac{\Gamma(\alpha+y_i)}{\Gamma(\alpha)y_i!}p_i^{y_i}(1-p_i)^\alpha$$
To get the waiting time distribution we note that:
$$Pr(T_i\leq t_i|\alpha\beta)=1-Pr(T_i> t_i|\alpha\beta)=1-Pr(Y_i(t_i)=0|\alpha\beta)$$
$$=1-(1-p_i)^\alpha=1-\left(1+\frac{t_i}{\beta}\right)^{-\alpha}$$
Differentiate this and you have the PDF:
$$p_{T_i}(t_i|\alpha\beta)=\frac{\alpha}{\beta}\left(1+\frac{t_i}{\beta}\right)^{-(\alpha+1)}$$
This is a member of the generalized Pareto distributions, type II. I would use this as your waiting time distribution.
To see the connection with the Poisson distribution, note that $\frac{\alpha}{\beta}=E(\lambda_i|\alpha\beta)$, so that if we set $\beta=\frac{\alpha}{\lambda}$ and then take the limit $\alpha\to\infty$ we get:
$$\lim_{\alpha\to\infty}\frac{\alpha}{\beta}\left(1+\frac{t_i}{\beta}\right)^{-(\alpha+1)}=\lim_{\alpha\to\infty}\lambda\left(1+\frac{\lambda t_i}{\alpha}\right)^{-(\alpha+1)}=\lambda\exp(-\lambda t_i)$$
This means that you can interpret $\frac{1}{\alpha}$ as an over-dispersion parameter. | Poisson is to exponential as Gamma-Poisson is to what? | This is a fairly straight forward problem. Although there is a connection between the Poisson and Negative Binomial distributions, I actually think this is unhelpful for your specific question as it | Poisson is to exponential as Gamma-Poisson is to what?
This is a fairly straight forward problem. Although there is a connection between the Poisson and Negative Binomial distributions, I actually think this is unhelpful for your specific question as it encourages people to think of negative binomial processes. Basically, you have a series of Poisson processes:
$$Y_i(t_i)|\lambda_i\sim Poisson(\lambda_i t_i)$$
Where $Y_i$ is the process and $t_i$ is the time you observe it, and $i$ denotes the individuals. And you are saying that these processes are "similar" by tying the rates together by a distribution:
$$\lambda_i\sim Gamma(\alpha,\beta)$$
On doing the integration/mxixing over $\lambda_i$, you have:
$$Y_i(t_i)|\alpha\beta\sim NegBin(\alpha,p_i)\;\;\; where \;\;p_i=\frac{t_i}{t_i+\beta}$$
This has a pmf of:
$$Pr(Y_i(t_i)=y_i|\alpha\beta) = \frac{\Gamma(\alpha+y_i)}{\Gamma(\alpha)y_i!}p_i^{y_i}(1-p_i)^\alpha$$
To get the waiting time distribution we note that:
$$Pr(T_i\leq t_i|\alpha\beta)=1-Pr(T_i> t_i|\alpha\beta)=1-Pr(Y_i(t_i)=0|\alpha\beta)$$
$$=1-(1-p_i)^\alpha=1-\left(1+\frac{t_i}{\beta}\right)^{-\alpha}$$
Differentiate this and you have the PDF:
$$p_{T_i}(t_i|\alpha\beta)=\frac{\alpha}{\beta}\left(1+\frac{t_i}{\beta}\right)^{-(\alpha+1)}$$
This is a member of the generalized Pareto distributions, type II. I would use this as your waiting time distribution.
To see the connection with the Poisson distribution, note that $\frac{\alpha}{\beta}=E(\lambda_i|\alpha\beta)$, so that if we set $\beta=\frac{\alpha}{\lambda}$ and then take the limit $\alpha\to\infty$ we get:
$$\lim_{\alpha\to\infty}\frac{\alpha}{\beta}\left(1+\frac{t_i}{\beta}\right)^{-(\alpha+1)}=\lim_{\alpha\to\infty}\lambda\left(1+\frac{\lambda t_i}{\alpha}\right)^{-(\alpha+1)}=\lambda\exp(-\lambda t_i)$$
This means that you can interpret $\frac{1}{\alpha}$ as an over-dispersion parameter. | Poisson is to exponential as Gamma-Poisson is to what?
This is a fairly straight forward problem. Although there is a connection between the Poisson and Negative Binomial distributions, I actually think this is unhelpful for your specific question as it |
17,481 | Poisson is to exponential as Gamma-Poisson is to what? | One possibility: Poisson is to Exponential as Negative-Binomial is to ... Exponential!
There is a pure-jump increasing Lévy process called the Negative Binomial Process such that at time $t$ the value has a negative binomial distribution. Unlike the Poisson process, the jumps are not almost surely $1$. Instead, they follow a logarithmic distribution. By the law of total variance, some of the variance comes from the number of jumps (scaled by the average size of the jumps), and some of the variance comes from the sizes of the jumps, and you can use this to check that it is overdispersed.
There may be other useful descriptions. See "Framing the negative binomial distribution for DNA sequencing."
Let me be more explicit about how the Negative Binomial Process described above can be constructed.
Choose $p \lt 1$.
Let $X_1, X_2, X_3, ...$ be IID with logarithmic distributions, so $P(x_i = k) = \frac{-1}{\log(1-p)} \frac{p^k}{k}.$
Let $N$ be a Poisson process with constant rate $-\log(1-p)$, so $N(t) = \text{Pois}(-t \log(1-p)).$
Let $NBP$ be the process so that
$$NBP(t) = \sum_{i=1}^{N(t)} X_i.$$
$NBP$ is a pure jump process with logarithmically distributed jumps. The gaps between jumps follow an exponential distribution with rate $-\log(1-p).$
I don't think it is obvious from this description that $NBP(t)$ has a negative binomial $NB(t,p)$ distribution, but there is a short proof using probability generating functions on Wikipedia, and Fisher also proved this when he introduced the logarithmic distribution to analyze the relative frequencies of species. | Poisson is to exponential as Gamma-Poisson is to what? | One possibility: Poisson is to Exponential as Negative-Binomial is to ... Exponential!
There is a pure-jump increasing Lévy process called the Negative Binomial Process such that at time $t$ the value | Poisson is to exponential as Gamma-Poisson is to what?
One possibility: Poisson is to Exponential as Negative-Binomial is to ... Exponential!
There is a pure-jump increasing Lévy process called the Negative Binomial Process such that at time $t$ the value has a negative binomial distribution. Unlike the Poisson process, the jumps are not almost surely $1$. Instead, they follow a logarithmic distribution. By the law of total variance, some of the variance comes from the number of jumps (scaled by the average size of the jumps), and some of the variance comes from the sizes of the jumps, and you can use this to check that it is overdispersed.
There may be other useful descriptions. See "Framing the negative binomial distribution for DNA sequencing."
Let me be more explicit about how the Negative Binomial Process described above can be constructed.
Choose $p \lt 1$.
Let $X_1, X_2, X_3, ...$ be IID with logarithmic distributions, so $P(x_i = k) = \frac{-1}{\log(1-p)} \frac{p^k}{k}.$
Let $N$ be a Poisson process with constant rate $-\log(1-p)$, so $N(t) = \text{Pois}(-t \log(1-p)).$
Let $NBP$ be the process so that
$$NBP(t) = \sum_{i=1}^{N(t)} X_i.$$
$NBP$ is a pure jump process with logarithmically distributed jumps. The gaps between jumps follow an exponential distribution with rate $-\log(1-p).$
I don't think it is obvious from this description that $NBP(t)$ has a negative binomial $NB(t,p)$ distribution, but there is a short proof using probability generating functions on Wikipedia, and Fisher also proved this when he introduced the logarithmic distribution to analyze the relative frequencies of species. | Poisson is to exponential as Gamma-Poisson is to what?
One possibility: Poisson is to Exponential as Negative-Binomial is to ... Exponential!
There is a pure-jump increasing Lévy process called the Negative Binomial Process such that at time $t$ the value |
17,482 | Poisson is to exponential as Gamma-Poisson is to what? | I am not able to comment yet so I apologize is this isn't a definitive solution.
You are asking for the appropriate distribution to use with an NB but appropriate isn't entirely defined. If an appropriate distribution means appropriate for explaining data and you are starting with an overdispersed Poisson then you may have to look further into the cause of the overdispersion. The NB doesn't distinguish between a Poisson with heterogeneous means or a positive occurrence dependence (that one event occurring increases the probability of another occurring). In continuous time there is also duration dependence, eg positive duration dependence means the passage of time increases the probability of an occurrence. It was also shown that negative duration dependence asymptotically causes an overdispersed Poisson[1]. This adds to the list of what might be the appropriate waiting time model. | Poisson is to exponential as Gamma-Poisson is to what? | I am not able to comment yet so I apologize is this isn't a definitive solution.
You are asking for the appropriate distribution to use with an NB but appropriate isn't entirely defined. If an appropr | Poisson is to exponential as Gamma-Poisson is to what?
I am not able to comment yet so I apologize is this isn't a definitive solution.
You are asking for the appropriate distribution to use with an NB but appropriate isn't entirely defined. If an appropriate distribution means appropriate for explaining data and you are starting with an overdispersed Poisson then you may have to look further into the cause of the overdispersion. The NB doesn't distinguish between a Poisson with heterogeneous means or a positive occurrence dependence (that one event occurring increases the probability of another occurring). In continuous time there is also duration dependence, eg positive duration dependence means the passage of time increases the probability of an occurrence. It was also shown that negative duration dependence asymptotically causes an overdispersed Poisson[1]. This adds to the list of what might be the appropriate waiting time model. | Poisson is to exponential as Gamma-Poisson is to what?
I am not able to comment yet so I apologize is this isn't a definitive solution.
You are asking for the appropriate distribution to use with an NB but appropriate isn't entirely defined. If an appropr |
17,483 | Expected value and variance of trace function | Since $X^TAX$ is a scalar, $$\text{Tr}(X^TAX)= X^TAX = \text{Tr}(AXX^T)$$ so that
$$\text{E}(X^TAX) = \text{E}(\text{Tr}(AXX^T)) = \text{Tr}(\text{E} (A XX^T)) =
\text{Tr}(A\text{E}(XX^T))$$.
Here we have used that the trace of a product are invariant under cyclical permutations of the factors, and that the trace is a linear operator, so commutes with expectation. The variance is a much more involved computation, which also need some higher moments of $X$. That calculation can be found in Seber: "Linear Regression Analysis" (Wiley) | Expected value and variance of trace function | Since $X^TAX$ is a scalar, $$\text{Tr}(X^TAX)= X^TAX = \text{Tr}(AXX^T)$$ so that
$$\text{E}(X^TAX) = \text{E}(\text{Tr}(AXX^T)) = \text{Tr}(\text{E} (A XX^T)) =
\text{Tr}(A\text{E}(XX^T))$$.
Here we | Expected value and variance of trace function
Since $X^TAX$ is a scalar, $$\text{Tr}(X^TAX)= X^TAX = \text{Tr}(AXX^T)$$ so that
$$\text{E}(X^TAX) = \text{E}(\text{Tr}(AXX^T)) = \text{Tr}(\text{E} (A XX^T)) =
\text{Tr}(A\text{E}(XX^T))$$.
Here we have used that the trace of a product are invariant under cyclical permutations of the factors, and that the trace is a linear operator, so commutes with expectation. The variance is a much more involved computation, which also need some higher moments of $X$. That calculation can be found in Seber: "Linear Regression Analysis" (Wiley) | Expected value and variance of trace function
Since $X^TAX$ is a scalar, $$\text{Tr}(X^TAX)= X^TAX = \text{Tr}(AXX^T)$$ so that
$$\text{E}(X^TAX) = \text{E}(\text{Tr}(AXX^T)) = \text{Tr}(\text{E} (A XX^T)) =
\text{Tr}(A\text{E}(XX^T))$$.
Here we |
17,484 | Density of normal distribution as dimensions increase | Lets take $X = (X_1,\dots,X_d) \sim N(0,I)$ : each $X_i$ is normal $N(0,1)$ and the $X_i$ are independant – I guess that’s what you mean with higher dimensions.
You would say that $X$ is within 1 sd of the mean when $||X|| < 1$ (the distance between X and its mean value is lower than 1). Now $||X||^2 = X_1^2 +\cdots+X_d^2\sim \chi^2(d)$ so this happens with probability $P( \xi < 1 )$ where $\xi\sim\chi^2(d)$. You can find this in good chi square tables...
Here are a few values:
$$\begin{array}{ll}
d& P(\xi < 1)\\
1 & 0.68\\
2 & 0.39 \\
3 & 0.20 \\
4 & 0.090 \\
5 & 0.037 \\
6 & 0.014 \\
7 & 0.0052 \\
8 & 0.0018\\
9 & 0.00056\\
10& 0.00017\\
\end{array}$$
And for 2 sd:
$$\begin{array}{ll}
d & P(\xi < 4)\\
1 & 0.95\\
2 & 0.86\\
3 & 0.74\\
4 & 0.59\\
5 & 0.45\\
6 & 0.32\\
7 & 0.22\\
8 & 0.14\\
9 & 0.089\\
10 & 0.053\\
\end{array}$$
You can get these values in R with commads like pchisq(1,df=1:10), pchisq(4,df=1:10), etc.
Post Scriptum As cardinal pointed out in the comments, one can estimate the asymptotic behaviour of these probabilities. The CDF of a $\chi^2(d)$ variable is
$$F_d(x) = P(d/2,x/2) = {\gamma(d/2, x/2) \over \Gamma(d/2)}$$
where $\gamma(s,y) = \int_0^y t^{s-1} e^{-t} \mathrm d t$ is the incomplete $\gamma$-function, and classicaly $\Gamma(s) = \int_0^\infty t^{s-1} e^{-t} \mathrm d t$.
When $s$ is an integer, repeated integration by parts shows that
$$ P(s,y) = e^{-y} \sum_{k=s}^\infty {y^k \over k!}, $$
which is the tail of the CDF of the Poisson distribution.
Now this sum is dominated by its first term (many thanks to cardinal): $P(s,y) \sim {y^s \over s!} e^{-y}$ for big $s$. We can apply this when $d$ is even:
$$P(\xi < x) = P(d/2,x/2) \sim {1 \over (d/2)!} \left({x\over 2}\right)^{d/2} e^{-x/2} \sim {1\over\sqrt{\pi d}}e^{{1\over 2}(d-x)} \left({x\over d}\right)^{d\over 2} \sim {1\over\sqrt\pi} e^{-{1\over 2}x} d^{-{1\over 2}d},$$
for big even $d$, the penultimate equivalence using Stirling formula. From this formula we see that the asymptotic decay is very fast as $d$ increase. | Density of normal distribution as dimensions increase | Lets take $X = (X_1,\dots,X_d) \sim N(0,I)$ : each $X_i$ is normal $N(0,1)$ and the $X_i$ are independant – I guess that’s what you mean with higher dimensions.
You would say that $X$ is within 1 sd | Density of normal distribution as dimensions increase
Lets take $X = (X_1,\dots,X_d) \sim N(0,I)$ : each $X_i$ is normal $N(0,1)$ and the $X_i$ are independant – I guess that’s what you mean with higher dimensions.
You would say that $X$ is within 1 sd of the mean when $||X|| < 1$ (the distance between X and its mean value is lower than 1). Now $||X||^2 = X_1^2 +\cdots+X_d^2\sim \chi^2(d)$ so this happens with probability $P( \xi < 1 )$ where $\xi\sim\chi^2(d)$. You can find this in good chi square tables...
Here are a few values:
$$\begin{array}{ll}
d& P(\xi < 1)\\
1 & 0.68\\
2 & 0.39 \\
3 & 0.20 \\
4 & 0.090 \\
5 & 0.037 \\
6 & 0.014 \\
7 & 0.0052 \\
8 & 0.0018\\
9 & 0.00056\\
10& 0.00017\\
\end{array}$$
And for 2 sd:
$$\begin{array}{ll}
d & P(\xi < 4)\\
1 & 0.95\\
2 & 0.86\\
3 & 0.74\\
4 & 0.59\\
5 & 0.45\\
6 & 0.32\\
7 & 0.22\\
8 & 0.14\\
9 & 0.089\\
10 & 0.053\\
\end{array}$$
You can get these values in R with commads like pchisq(1,df=1:10), pchisq(4,df=1:10), etc.
Post Scriptum As cardinal pointed out in the comments, one can estimate the asymptotic behaviour of these probabilities. The CDF of a $\chi^2(d)$ variable is
$$F_d(x) = P(d/2,x/2) = {\gamma(d/2, x/2) \over \Gamma(d/2)}$$
where $\gamma(s,y) = \int_0^y t^{s-1} e^{-t} \mathrm d t$ is the incomplete $\gamma$-function, and classicaly $\Gamma(s) = \int_0^\infty t^{s-1} e^{-t} \mathrm d t$.
When $s$ is an integer, repeated integration by parts shows that
$$ P(s,y) = e^{-y} \sum_{k=s}^\infty {y^k \over k!}, $$
which is the tail of the CDF of the Poisson distribution.
Now this sum is dominated by its first term (many thanks to cardinal): $P(s,y) \sim {y^s \over s!} e^{-y}$ for big $s$. We can apply this when $d$ is even:
$$P(\xi < x) = P(d/2,x/2) \sim {1 \over (d/2)!} \left({x\over 2}\right)^{d/2} e^{-x/2} \sim {1\over\sqrt{\pi d}}e^{{1\over 2}(d-x)} \left({x\over d}\right)^{d\over 2} \sim {1\over\sqrt\pi} e^{-{1\over 2}x} d^{-{1\over 2}d},$$
for big even $d$, the penultimate equivalence using Stirling formula. From this formula we see that the asymptotic decay is very fast as $d$ increase. | Density of normal distribution as dimensions increase
Lets take $X = (X_1,\dots,X_d) \sim N(0,I)$ : each $X_i$ is normal $N(0,1)$ and the $X_i$ are independant – I guess that’s what you mean with higher dimensions.
You would say that $X$ is within 1 sd |
17,485 | How is ARMA/ARIMA related to mixed effects modeling? | I think the simplest way to look at it is to note that ARMA and similar models are designed to do different things than multi-level models, and use different data.
Time series analysis usually has long time series (possibly of hundreds or even thousands of time points) and the primary goal is to look at how a single variable changes over time. There are sophisticated methods to deal with many problems - not just autocorrelation, but seasonality and other periodic changes and so on.
Multilevel models are extensions from regression. They usually have relatively few time points (although they can have many) and the primary goal is to examine the relationship between a dependent variable and several independent variables. These models are not as good at dealing with complex relationships between a variable and time, partly because they usually have fewer time points (it's hard to look at seasonality if you don't have multiple data for each season). | How is ARMA/ARIMA related to mixed effects modeling? | I think the simplest way to look at it is to note that ARMA and similar models are designed to do different things than multi-level models, and use different data.
Time series analysis usually has lon | How is ARMA/ARIMA related to mixed effects modeling?
I think the simplest way to look at it is to note that ARMA and similar models are designed to do different things than multi-level models, and use different data.
Time series analysis usually has long time series (possibly of hundreds or even thousands of time points) and the primary goal is to look at how a single variable changes over time. There are sophisticated methods to deal with many problems - not just autocorrelation, but seasonality and other periodic changes and so on.
Multilevel models are extensions from regression. They usually have relatively few time points (although they can have many) and the primary goal is to examine the relationship between a dependent variable and several independent variables. These models are not as good at dealing with complex relationships between a variable and time, partly because they usually have fewer time points (it's hard to look at seasonality if you don't have multiple data for each season). | How is ARMA/ARIMA related to mixed effects modeling?
I think the simplest way to look at it is to note that ARMA and similar models are designed to do different things than multi-level models, and use different data.
Time series analysis usually has lon |
17,486 | How is ARMA/ARIMA related to mixed effects modeling? | ARMA/ARIMA are univariate models that optimize how to use the past of a single series to predict that single series. One can augment these models with empirically identified Intervention Variables such as Pulses, Level Shifts , Seasonal Pulses and Local Time Trends BUT they are still fundamentally non-causal as no user-suggested input series are in place. The multivariate extension of these models is call XARMAX or more generally Transfer Function Models which use PDL/ADL structures on the inputs and employ any needed ARMA/ARIMA structure on the remainder. These models can also be robustified by incorporating empirically identifiable deterministic inputs. Thus both of these models can be considered Applications to longitudinal (repeated measures) data. Now the Wikipedia article on multi-level models refers to their application to time series/longitudinal data by assuming certain primitive/trivial i.e. non-analytical structures like "The simplest models assume that the effect of time is linear. Polynomial models can be specified to allow for quadratic or cubic effects of time".
One can extend the Transfer Function model to cover multiple groups thus evolving to Pooled Cross-section time series analysis where the appropriate structure (lags/leads) can be used in conjunction with ARIMA structure to form both local models and an overall model. | How is ARMA/ARIMA related to mixed effects modeling? | ARMA/ARIMA are univariate models that optimize how to use the past of a single series to predict that single series. One can augment these models with empirically identified Intervention Variables suc | How is ARMA/ARIMA related to mixed effects modeling?
ARMA/ARIMA are univariate models that optimize how to use the past of a single series to predict that single series. One can augment these models with empirically identified Intervention Variables such as Pulses, Level Shifts , Seasonal Pulses and Local Time Trends BUT they are still fundamentally non-causal as no user-suggested input series are in place. The multivariate extension of these models is call XARMAX or more generally Transfer Function Models which use PDL/ADL structures on the inputs and employ any needed ARMA/ARIMA structure on the remainder. These models can also be robustified by incorporating empirically identifiable deterministic inputs. Thus both of these models can be considered Applications to longitudinal (repeated measures) data. Now the Wikipedia article on multi-level models refers to their application to time series/longitudinal data by assuming certain primitive/trivial i.e. non-analytical structures like "The simplest models assume that the effect of time is linear. Polynomial models can be specified to allow for quadratic or cubic effects of time".
One can extend the Transfer Function model to cover multiple groups thus evolving to Pooled Cross-section time series analysis where the appropriate structure (lags/leads) can be used in conjunction with ARIMA structure to form both local models and an overall model. | How is ARMA/ARIMA related to mixed effects modeling?
ARMA/ARIMA are univariate models that optimize how to use the past of a single series to predict that single series. One can augment these models with empirically identified Intervention Variables suc |
17,487 | What is the best statistical test for a time series? [closed] | You will need to specify precisely what you mean by "different". You will also need to specify what assumptions you are willing to make about the serial correlation structure within each time series.
With t-tests, you are comparing the mean of each group and you are assuming that the groups consist of independent observations with equal variances (the latter is sometimes relaxed). When testing time series, the assumption of independence is usually not reasonable, but then you need to replace it with a specified correlation structure -- e.g., you might assume that the time series follow AR(1) processes with equal autocorrelation. Consequently, even comparing the means of two or more time series is considerably more difficult than with independent data.
I would carefully specify what assumptions I was willing to make about each time series, and what I was wishing to compare, and then use a parametric bootstrap (based on the assumed model) to carry out the test. | What is the best statistical test for a time series? [closed] | You will need to specify precisely what you mean by "different". You will also need to specify what assumptions you are willing to make about the serial correlation structure within each time series. | What is the best statistical test for a time series? [closed]
You will need to specify precisely what you mean by "different". You will also need to specify what assumptions you are willing to make about the serial correlation structure within each time series.
With t-tests, you are comparing the mean of each group and you are assuming that the groups consist of independent observations with equal variances (the latter is sometimes relaxed). When testing time series, the assumption of independence is usually not reasonable, but then you need to replace it with a specified correlation structure -- e.g., you might assume that the time series follow AR(1) processes with equal autocorrelation. Consequently, even comparing the means of two or more time series is considerably more difficult than with independent data.
I would carefully specify what assumptions I was willing to make about each time series, and what I was wishing to compare, and then use a parametric bootstrap (based on the assumed model) to carry out the test. | What is the best statistical test for a time series? [closed]
You will need to specify precisely what you mean by "different". You will also need to specify what assumptions you are willing to make about the serial correlation structure within each time series. |
17,488 | What is the best statistical test for a time series? [closed] | Maybe repeated measures anova is what you want. It allows you to compare the subjects (inter subject factors) while taking the correlated structure of the "time series" per subject (intra subject factor). It is an easy but dated method and can be found in the context of "general linear models", it needs some additional features (e.g. sphericity). Another way could be mixed linear models which allow for more general correlations structures (even AR(1) like Rob suggested) and unbalanced data. | What is the best statistical test for a time series? [closed] | Maybe repeated measures anova is what you want. It allows you to compare the subjects (inter subject factors) while taking the correlated structure of the "time series" per subject (intra subject fact | What is the best statistical test for a time series? [closed]
Maybe repeated measures anova is what you want. It allows you to compare the subjects (inter subject factors) while taking the correlated structure of the "time series" per subject (intra subject factor). It is an easy but dated method and can be found in the context of "general linear models", it needs some additional features (e.g. sphericity). Another way could be mixed linear models which allow for more general correlations structures (even AR(1) like Rob suggested) and unbalanced data. | What is the best statistical test for a time series? [closed]
Maybe repeated measures anova is what you want. It allows you to compare the subjects (inter subject factors) while taking the correlated structure of the "time series" per subject (intra subject fact |
17,489 | What is the best statistical test for a time series? [closed] | If you want to assume simple linear trend, you can take the difference of each data set at the various time points and test that the slope of the line is zero.
-Ralph Winters | What is the best statistical test for a time series? [closed] | If you want to assume simple linear trend, you can take the difference of each data set at the various time points and test that the slope of the line is zero.
-Ralph Winters | What is the best statistical test for a time series? [closed]
If you want to assume simple linear trend, you can take the difference of each data set at the various time points and test that the slope of the line is zero.
-Ralph Winters | What is the best statistical test for a time series? [closed]
If you want to assume simple linear trend, you can take the difference of each data set at the various time points and test that the slope of the line is zero.
-Ralph Winters |
17,490 | @whuber 's generation of a random variable with fixed covariance structure | As a point for further elaboration, here is the explanation in the thread you reference:
If it's mathematically possible, [this method] will find an $X_{Y_1,Y_2,\ldots,Y_k;\rho_1,\rho_2,\ldots,\rho_k}$ having specified correlations [between $X$ and] an entire set of $Y_i$. Just use ordinary least squares to take out the effects of all the $Y_i$ from $X$ and form a suitable linear combination of the $Y_i$ and the residuals. (It helps to do this in terms of a dual basis for $Y$, which is obtained by computing a pseudo-inverse. The following code uses the SVD of $Y$ to accomplish that.)
(I apologize for the reversal from the usual roles of $X$ (which here is treated as a response variable in a multiple regression) and $Y$ (which here is a collection of explanatory or regressor variables). This notation was adopted out of respect for the original question.)
The R code given to specify this procedure is sufficiently compact to be reproduced here:
y <- scale(y) # Makes computations simpler
e <- residuals(lm(x ~ y)) # Take out the columns of matrix `y`
y.dual <- with(svd(y), (n-1)*u %*% diag(ifelse(d > 0, 1/d, 0)) %*% t(v))
sigma2 <- c((1 - rho %*% cov(y.dual) %*% rho) / var(e))
return(y.dual %*% rho + sqrt(sigma2)*e)
Let's go through this recipe step by step.
Taking out the effects of $Y$. Ordinary Least Squares finds a vector $\beta=(\beta_i)$ of $k$ coefficients for which the residuals $$e = X - Y\beta$$ are orthogonal to (have zero covariance with) the vector space spanned by the columns of $Y = \pmatrix{Y_1,&Y_2,&\cdots, & Y_k}.$ (These orthogonality relations are known as the Normal Equations.) The line of code
e <- residuals(lm(x ~ y))
carries out this calculation.
A linear combination. By definition, a linear combination of $Y$ and the residuals $e$ can be written in terms of a number $\sigma $ and $k$-vector $\alpha$ as $$Z=\sigma e + Y\alpha =\sigma e + \alpha_1 Y_1 + \cdots + \alpha_k Y_k.$$ By virtue of the Normal Equations, the covariance between any $Y_i$ and such a combination is $$\operatorname{Cov}(Z, Y_i) = \sigma \operatorname{Cov}(e,Y_i) + \operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right) = \operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right).\tag{1}$$ Ultimately, we want to find coefficients $\alpha_j$ that give the right hand side the right values to achieve the desired correlations $\rho = (\rho_i).$
A dual basis. This problem of finding the $\alpha_j$ is easily solved with a dual basis. Without loss of generality, re-index the $Y_i$ if necessary so that the first $d$ of them are linearly independent and span the same space spanned by all the $Y_i:$ that is, they form a basis. We seek a collection of $d$ vectors $W_j,$ each of which is a linear combination of the $Y_j, j\le d,$ for which $$\operatorname{Cov}(W_i,Y_j) = 0\tag{2}$$ whenever $i\ne j$ and $j \le d.$ We may scale the $W_j$ so that $$\operatorname{Var}(W_j)=1.\tag{3}$$ $(W_j)$ is a dual basis associated with the $Y_i.$
As described in the text, such a matrix $W$ can be found using the Singular Value Decomposition (SVD) $$Y = U\, D\, V^\prime$$ by inverting the diagonal matrix $D$ (leaving any diagonal zeros alone) to create a pseudo-inverse $D^{-}$ whose first $d$ diagonal values are nonzero and forming $$Y^{-} = U\, D^{-}\, V^\prime.$$ You may check that the $d\times d$ block of $$(Y^{-})^\prime Y = (V\, D^{-}\, U^\prime)\, (U\, D\, V^\prime) = V\, I^{-}\, V^\prime = \pmatrix{\mathbb{I}_d & * \\ * & *}$$ is the identity matrix, which is just a compact way of expressing formulas $(2)$ and $(3)$ simultaneously. This is what the code
y.dual <- with(svd(y), (n-1)*u %*% diag(ifelse(d > threshold, 1/d, 0)) %*% t(v))
does. It turns out that this formula for $W$ works even when the first $d$ columns of $Y$ are not linearly independent. (Thinking of SVD in terms of geometric operations makes this apparent.) This obviates any need to execute the preliminary re-indexing step of the $Y_i.$
A suitable linear combination. Returning to $(1),$ express the linear combination $Y\alpha$ in terms of the dual basis, $$Y\alpha = \sum_{i=1}^d \gamma_jW_j.$$ This re-expresses $(1)$ as $$\operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right) = \operatorname{Cov}\left(\sum_{j=1}^d \gamma_jW_j, Y_i\right) = \sum_{j=1}^d \gamma_j \operatorname{Cov}\left(W_j, Y_i\right) = \gamma_i.$$ Consequently, using a standard formula for correlations, the $d$ equations we need to solve are $$\rho_i = \operatorname{Cor}(Z, Y_i) = \frac{\operatorname{Cov}(Z, Y_i)}{\operatorname{sd}(Z)\operatorname{sd}(Y_i)} = \frac{\gamma_i}{\operatorname{sd}(Z)\operatorname{sd}(Y_i)}.\tag{4}$$
The final step. As a preliminary step, we may as well have scaled the $Y_i$ to give them unit standard deviations. (The line of code y <- scale(y, center=FALSE) does that.) We're going to make sure $Z $ also has a unit standard deviation, so that the previous formula $(4)$ actually gives the correlation. That is, the solution by all rights ought to be $\gamma_i = \rho_i.$ If that's possible, then $$1 = \operatorname{Var}(Z) = \sigma ^2 \operatorname{Var}(e) + \operatorname{Var}(W\rho).$$ Consequently, assuming the residual vector $e$ is nonzero, $$\sigma ^2 = \frac{1 - \operatorname{Var}(W\rho)}{\operatorname{Var}(e)} = \frac{1 - \rho^\prime \operatorname{Cov}(W)\rho}{\operatorname{Var}(e)}.$$ This formula (omitted in the present question) is implemented in the code as
sigma2 <- c((1 - rho %*% cov(y.dual) %*% rho) / var(e))
Finally, the solution $Z = \sigma e + Y\alpha = \sigma e + W\gamma = W\rho + \sigma e$ is implemented in the code as
y.dual %*% rho + sqrt(sigma2)*e | @whuber 's generation of a random variable with fixed covariance structure | As a point for further elaboration, here is the explanation in the thread you reference:
If it's mathematically possible, [this method] will find an $X_{Y_1,Y_2,\ldots,Y_k;\rho_1,\rho_2,\ldots,\rho_k | @whuber 's generation of a random variable with fixed covariance structure
As a point for further elaboration, here is the explanation in the thread you reference:
If it's mathematically possible, [this method] will find an $X_{Y_1,Y_2,\ldots,Y_k;\rho_1,\rho_2,\ldots,\rho_k}$ having specified correlations [between $X$ and] an entire set of $Y_i$. Just use ordinary least squares to take out the effects of all the $Y_i$ from $X$ and form a suitable linear combination of the $Y_i$ and the residuals. (It helps to do this in terms of a dual basis for $Y$, which is obtained by computing a pseudo-inverse. The following code uses the SVD of $Y$ to accomplish that.)
(I apologize for the reversal from the usual roles of $X$ (which here is treated as a response variable in a multiple regression) and $Y$ (which here is a collection of explanatory or regressor variables). This notation was adopted out of respect for the original question.)
The R code given to specify this procedure is sufficiently compact to be reproduced here:
y <- scale(y) # Makes computations simpler
e <- residuals(lm(x ~ y)) # Take out the columns of matrix `y`
y.dual <- with(svd(y), (n-1)*u %*% diag(ifelse(d > 0, 1/d, 0)) %*% t(v))
sigma2 <- c((1 - rho %*% cov(y.dual) %*% rho) / var(e))
return(y.dual %*% rho + sqrt(sigma2)*e)
Let's go through this recipe step by step.
Taking out the effects of $Y$. Ordinary Least Squares finds a vector $\beta=(\beta_i)$ of $k$ coefficients for which the residuals $$e = X - Y\beta$$ are orthogonal to (have zero covariance with) the vector space spanned by the columns of $Y = \pmatrix{Y_1,&Y_2,&\cdots, & Y_k}.$ (These orthogonality relations are known as the Normal Equations.) The line of code
e <- residuals(lm(x ~ y))
carries out this calculation.
A linear combination. By definition, a linear combination of $Y$ and the residuals $e$ can be written in terms of a number $\sigma $ and $k$-vector $\alpha$ as $$Z=\sigma e + Y\alpha =\sigma e + \alpha_1 Y_1 + \cdots + \alpha_k Y_k.$$ By virtue of the Normal Equations, the covariance between any $Y_i$ and such a combination is $$\operatorname{Cov}(Z, Y_i) = \sigma \operatorname{Cov}(e,Y_i) + \operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right) = \operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right).\tag{1}$$ Ultimately, we want to find coefficients $\alpha_j$ that give the right hand side the right values to achieve the desired correlations $\rho = (\rho_i).$
A dual basis. This problem of finding the $\alpha_j$ is easily solved with a dual basis. Without loss of generality, re-index the $Y_i$ if necessary so that the first $d$ of them are linearly independent and span the same space spanned by all the $Y_i:$ that is, they form a basis. We seek a collection of $d$ vectors $W_j,$ each of which is a linear combination of the $Y_j, j\le d,$ for which $$\operatorname{Cov}(W_i,Y_j) = 0\tag{2}$$ whenever $i\ne j$ and $j \le d.$ We may scale the $W_j$ so that $$\operatorname{Var}(W_j)=1.\tag{3}$$ $(W_j)$ is a dual basis associated with the $Y_i.$
As described in the text, such a matrix $W$ can be found using the Singular Value Decomposition (SVD) $$Y = U\, D\, V^\prime$$ by inverting the diagonal matrix $D$ (leaving any diagonal zeros alone) to create a pseudo-inverse $D^{-}$ whose first $d$ diagonal values are nonzero and forming $$Y^{-} = U\, D^{-}\, V^\prime.$$ You may check that the $d\times d$ block of $$(Y^{-})^\prime Y = (V\, D^{-}\, U^\prime)\, (U\, D\, V^\prime) = V\, I^{-}\, V^\prime = \pmatrix{\mathbb{I}_d & * \\ * & *}$$ is the identity matrix, which is just a compact way of expressing formulas $(2)$ and $(3)$ simultaneously. This is what the code
y.dual <- with(svd(y), (n-1)*u %*% diag(ifelse(d > threshold, 1/d, 0)) %*% t(v))
does. It turns out that this formula for $W$ works even when the first $d$ columns of $Y$ are not linearly independent. (Thinking of SVD in terms of geometric operations makes this apparent.) This obviates any need to execute the preliminary re-indexing step of the $Y_i.$
A suitable linear combination. Returning to $(1),$ express the linear combination $Y\alpha$ in terms of the dual basis, $$Y\alpha = \sum_{i=1}^d \gamma_jW_j.$$ This re-expresses $(1)$ as $$\operatorname{Cov}\left(\sum_{j=1}^k \alpha_j Y_j, Y_i\right) = \operatorname{Cov}\left(\sum_{j=1}^d \gamma_jW_j, Y_i\right) = \sum_{j=1}^d \gamma_j \operatorname{Cov}\left(W_j, Y_i\right) = \gamma_i.$$ Consequently, using a standard formula for correlations, the $d$ equations we need to solve are $$\rho_i = \operatorname{Cor}(Z, Y_i) = \frac{\operatorname{Cov}(Z, Y_i)}{\operatorname{sd}(Z)\operatorname{sd}(Y_i)} = \frac{\gamma_i}{\operatorname{sd}(Z)\operatorname{sd}(Y_i)}.\tag{4}$$
The final step. As a preliminary step, we may as well have scaled the $Y_i$ to give them unit standard deviations. (The line of code y <- scale(y, center=FALSE) does that.) We're going to make sure $Z $ also has a unit standard deviation, so that the previous formula $(4)$ actually gives the correlation. That is, the solution by all rights ought to be $\gamma_i = \rho_i.$ If that's possible, then $$1 = \operatorname{Var}(Z) = \sigma ^2 \operatorname{Var}(e) + \operatorname{Var}(W\rho).$$ Consequently, assuming the residual vector $e$ is nonzero, $$\sigma ^2 = \frac{1 - \operatorname{Var}(W\rho)}{\operatorname{Var}(e)} = \frac{1 - \rho^\prime \operatorname{Cov}(W)\rho}{\operatorname{Var}(e)}.$$ This formula (omitted in the present question) is implemented in the code as
sigma2 <- c((1 - rho %*% cov(y.dual) %*% rho) / var(e))
Finally, the solution $Z = \sigma e + Y\alpha = \sigma e + W\gamma = W\rho + \sigma e$ is implemented in the code as
y.dual %*% rho + sqrt(sigma2)*e | @whuber 's generation of a random variable with fixed covariance structure
As a point for further elaboration, here is the explanation in the thread you reference:
If it's mathematically possible, [this method] will find an $X_{Y_1,Y_2,\ldots,Y_k;\rho_1,\rho_2,\ldots,\rho_k |
17,491 | How are PQL, REML, ML, Laplace, Gauss-Hermite related to each other? | Generalized Linear Mixed Models (GLMMs) have the following general representation:
$$\left\{
\begin{array}{l}
Y_i \mid b_i \sim \mathcal F_\psi,\\\\
b_i \sim \mathcal N(0, D),
\end{array}
\right.$$
where $Y_i$ is the response for the $i$-th sample unit and $b_i$ is the vector of random effects for this unit. The response $Y_i$ conditional on the random effects has a distribution $\mathcal F$ parameterized by the vector $\psi$, and the random effects are typically assumed to follow a multivariate normal distribution with mean 0 and variance-covariance matrix $D$. Some standard GLMMs assume that the distribution $\mathcal F_\psi$ is the binomial, Poisson, negative binomial, Beta or Gamma distribution.
The likelihood function of theses models has the following general form $$L(\theta) = \prod_{i = 1}^n \int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i,$$
in which the first term is the probability mass or probability density function of $\mathcal F_\psi$, and the second term is the probability density function of the multivariate normal distribution for the random effects. Also, $\theta = (\psi, \mbox{vech}(D))$.
The problem is that the integral in the definition of this likelihood function does not have a closed-form solution. Hence, to estimate the parameters in these models under maximum likelihood, you need to somehow approximate this integral. In the literature, two main types of approximation have been proposed.
Approximation of the integrand: These methods entail approximating the product of the two terms $p(y_i \mid b_i; \psi) \times p(b_i; D)$ by a multivariate normal distribution because for this distribution we can solve the integral. The PQL and Laplace approximation methods fall into this category.
Approximation of the integral: These methods entail approximation of the whole integral by a (weighted) sum, i.e.,
$$\int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i \approx \sum_k \varpi_k \, p(y_i \mid b_k; \psi) \, p(b_k; D).$$
Some methods that fall into this category are the Monte Carlo and adaptive Gaussian quarature approximations.
Merits & Flaws
The Approximation of the integrand methods are in general faster than then Approximation of the integral ones. However, they do not provide any control of the approximation error. For this reason, these methods work better when the product of the two terms can be well approximated by a multivariate normal distribution. This is when the data are more continuous. That is, in Binomial data with large number of trials and Poisson data with large expected counts.
The Approximation of the integral methods are slower, but they do provide control of the approximation error by using more terms in the summation. That is, by considering a larger Monte Carlo sample or more quadrature points. Hence, these methods will work better in binary data or Poisson data with low expected counts.
Just to mention that there are some links between the two classes of methods. For example, the Laplace approximation is equivalent to the adaptive Gaussian quadrature rule with one quadrature point.
Finally, the REML method is more relevant in the estimation of linear mixed models for which the integral does have a closed-form solution, but the point is how to estimate the variance components, i.e., the unique elements in the specification of the $D$ covariance matrix. The classic maximum likelihood procedure is known to produce biased results for estimating these parameters, especially in small samples, because it does not account for the fact that to estimate the variance parameters, you first need to estimate the mean parameters. The REML approach does account for that and is a generalization of the idea why in the sample variance we need to divide by $n - 1$ to get an unbiased estimate of the population variance instead of $n$, which is the maximum likelihood estimator, with $n$ being the sample size.
EDIT: PQL in Combination with REML
The approximation performed by the PQL method results in a new response vector $Y_i^*$, which is a transformation of the original data $Y_i$ that attempts to make $Y_i^*$ normally distributed. Hence, fitting a GLMM is equivalent to fitting a linear mixed model for $Y_i^*$, and as mentioned above, in the linear mixed model you may select to estimate the variance components either with maximum likelihood (ML) or restricted maximum likelihood (REML). | How are PQL, REML, ML, Laplace, Gauss-Hermite related to each other? | Generalized Linear Mixed Models (GLMMs) have the following general representation:
$$\left\{
\begin{array}{l}
Y_i \mid b_i \sim \mathcal F_\psi,\\\\
b_i \sim \mathcal N(0, D),
\end{array}
\right.$$
wh | How are PQL, REML, ML, Laplace, Gauss-Hermite related to each other?
Generalized Linear Mixed Models (GLMMs) have the following general representation:
$$\left\{
\begin{array}{l}
Y_i \mid b_i \sim \mathcal F_\psi,\\\\
b_i \sim \mathcal N(0, D),
\end{array}
\right.$$
where $Y_i$ is the response for the $i$-th sample unit and $b_i$ is the vector of random effects for this unit. The response $Y_i$ conditional on the random effects has a distribution $\mathcal F$ parameterized by the vector $\psi$, and the random effects are typically assumed to follow a multivariate normal distribution with mean 0 and variance-covariance matrix $D$. Some standard GLMMs assume that the distribution $\mathcal F_\psi$ is the binomial, Poisson, negative binomial, Beta or Gamma distribution.
The likelihood function of theses models has the following general form $$L(\theta) = \prod_{i = 1}^n \int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i,$$
in which the first term is the probability mass or probability density function of $\mathcal F_\psi$, and the second term is the probability density function of the multivariate normal distribution for the random effects. Also, $\theta = (\psi, \mbox{vech}(D))$.
The problem is that the integral in the definition of this likelihood function does not have a closed-form solution. Hence, to estimate the parameters in these models under maximum likelihood, you need to somehow approximate this integral. In the literature, two main types of approximation have been proposed.
Approximation of the integrand: These methods entail approximating the product of the two terms $p(y_i \mid b_i; \psi) \times p(b_i; D)$ by a multivariate normal distribution because for this distribution we can solve the integral. The PQL and Laplace approximation methods fall into this category.
Approximation of the integral: These methods entail approximation of the whole integral by a (weighted) sum, i.e.,
$$\int p(y_i \mid b_i; \psi) \, p(b_i; D) \, db_i \approx \sum_k \varpi_k \, p(y_i \mid b_k; \psi) \, p(b_k; D).$$
Some methods that fall into this category are the Monte Carlo and adaptive Gaussian quarature approximations.
Merits & Flaws
The Approximation of the integrand methods are in general faster than then Approximation of the integral ones. However, they do not provide any control of the approximation error. For this reason, these methods work better when the product of the two terms can be well approximated by a multivariate normal distribution. This is when the data are more continuous. That is, in Binomial data with large number of trials and Poisson data with large expected counts.
The Approximation of the integral methods are slower, but they do provide control of the approximation error by using more terms in the summation. That is, by considering a larger Monte Carlo sample or more quadrature points. Hence, these methods will work better in binary data or Poisson data with low expected counts.
Just to mention that there are some links between the two classes of methods. For example, the Laplace approximation is equivalent to the adaptive Gaussian quadrature rule with one quadrature point.
Finally, the REML method is more relevant in the estimation of linear mixed models for which the integral does have a closed-form solution, but the point is how to estimate the variance components, i.e., the unique elements in the specification of the $D$ covariance matrix. The classic maximum likelihood procedure is known to produce biased results for estimating these parameters, especially in small samples, because it does not account for the fact that to estimate the variance parameters, you first need to estimate the mean parameters. The REML approach does account for that and is a generalization of the idea why in the sample variance we need to divide by $n - 1$ to get an unbiased estimate of the population variance instead of $n$, which is the maximum likelihood estimator, with $n$ being the sample size.
EDIT: PQL in Combination with REML
The approximation performed by the PQL method results in a new response vector $Y_i^*$, which is a transformation of the original data $Y_i$ that attempts to make $Y_i^*$ normally distributed. Hence, fitting a GLMM is equivalent to fitting a linear mixed model for $Y_i^*$, and as mentioned above, in the linear mixed model you may select to estimate the variance components either with maximum likelihood (ML) or restricted maximum likelihood (REML). | How are PQL, REML, ML, Laplace, Gauss-Hermite related to each other?
Generalized Linear Mixed Models (GLMMs) have the following general representation:
$$\left\{
\begin{array}{l}
Y_i \mid b_i \sim \mathcal F_\psi,\\\\
b_i \sim \mathcal N(0, D),
\end{array}
\right.$$
wh |
17,492 | What is the name for the average of the largest and the smallest values in a given data set? | It's called the midrange and while it's not the most widely used statistic in the world it does have some relevance to the uniform distribution.
Let's introduce the order statistic notation: if have $n$ i.i.d. random variables $X_1, ..., X_n$, then the notation $X_{(i)}$ is used to refer to the $i$-th largest of the set $\{X_1, ..., X_n\}$. Thus we have:
$$ X_{(1)} ≤ X_{(2)} ≤···≤ X_{(n)} \tag{1} $$
Where $X_{(1)}$ is the minimum and $X_{(n)}$ is the maximum element. Then range and midrange are defined as:
$$ \begin{align}
R & = X_{(n)} - X_{(1)} \tag{2} \\
A & = \frac{X_{(1)} + X_{(n)}}{2} \tag{3} \\
\end{align}
$$
These formulas are taken from CRC Standard Probability and Statistics Tables and Formulae, section 4.6.6.
If $X_i$ is assumed to have a uniform distribution $X_i \sim U(\alpha, \beta)$, where $\alpha$ and $\beta$ are the lower and upper bounds respectively, then we can give the MLE estimates in terms of these formulas:
$$
\begin{align}
\hat{\alpha} & = X_{(1)} \tag{4} \\
\hat{\beta} & = X_{(n)} \tag{5}
\end{align}
$$
The mean of the resulting distribution is the same as the midrange:
$$
\begin{align}
\mu & = A = \frac{X_{(1)} + X_{(n)}}{2} \tag{6} \\
\end{align}
$$
This is probably the only use for this particular statistic. | What is the name for the average of the largest and the smallest values in a given data set? | It's called the midrange and while it's not the most widely used statistic in the world it does have some relevance to the uniform distribution.
Let's introduce the order statistic notation: if have | What is the name for the average of the largest and the smallest values in a given data set?
It's called the midrange and while it's not the most widely used statistic in the world it does have some relevance to the uniform distribution.
Let's introduce the order statistic notation: if have $n$ i.i.d. random variables $X_1, ..., X_n$, then the notation $X_{(i)}$ is used to refer to the $i$-th largest of the set $\{X_1, ..., X_n\}$. Thus we have:
$$ X_{(1)} ≤ X_{(2)} ≤···≤ X_{(n)} \tag{1} $$
Where $X_{(1)}$ is the minimum and $X_{(n)}$ is the maximum element. Then range and midrange are defined as:
$$ \begin{align}
R & = X_{(n)} - X_{(1)} \tag{2} \\
A & = \frac{X_{(1)} + X_{(n)}}{2} \tag{3} \\
\end{align}
$$
These formulas are taken from CRC Standard Probability and Statistics Tables and Formulae, section 4.6.6.
If $X_i$ is assumed to have a uniform distribution $X_i \sim U(\alpha, \beta)$, where $\alpha$ and $\beta$ are the lower and upper bounds respectively, then we can give the MLE estimates in terms of these formulas:
$$
\begin{align}
\hat{\alpha} & = X_{(1)} \tag{4} \\
\hat{\beta} & = X_{(n)} \tag{5}
\end{align}
$$
The mean of the resulting distribution is the same as the midrange:
$$
\begin{align}
\mu & = A = \frac{X_{(1)} + X_{(n)}}{2} \tag{6} \\
\end{align}
$$
This is probably the only use for this particular statistic. | What is the name for the average of the largest and the smallest values in a given data set?
It's called the midrange and while it's not the most widely used statistic in the world it does have some relevance to the uniform distribution.
Let's introduce the order statistic notation: if have |
17,493 | Normalizing vs Scaling before PCA | Scaling (what I would call centering and scaling) is very important for PCA because of the way that the principal components are calculated. PCA is solved via the Singular Value Decomposition, which finds linear subspaces which best represent your data in the squared sense. The two parts I've italicized are the reason that we center and scale (respectively).
Linear Subspaces are an important topic of study in Linear Algebra and the most important consequence of a linear subspace for PCA is that it has to go through the origin, the point [0, 0, ..., 0]. So if, say, you're measuring something like the GDP and population of a country, your data are likely to live very far from the origin, and be poorly approximated by any linear subspace. By centering our data, we guarantee that they exist near the origin, and it may be possible to approximate them with a low dimension linear subspace. In your case your data seem to all be positive, so they are most certainly not centered around 0 prior to preprocessing.
Here is an example of 2D a dataset far from the origin, which gets a useless first component until it is centered:
Scaling is important because SVD approximates in the sum of squares sense, so if one variable is on a different scale than another, it will dominate the PCA procedure, and the low D plot will really just be visualizing that dimension.
I will illustrate with an example in python.
Let's first set up an environment:
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale, normalize
import matplotlib.pyplot as plt
plt.ion()
# For reproducibility
np.random.seed(123)
We're going to generate data that are standard normal/uncorrelated in 4 dimensions, but with one additional variable that takes value either 0 or 5 randomly, giving a 5 dimensional dataset that we wish to visualize:
N = 200
P = 5
rho = 0.5
X = np.random.normal(size=[N,P])
X = np.append(X, 3*np.random.choice(2, size = [N,1]), axis = 1)
We will first do PCA without any preprocessing:
# No preprocessing:
pca = PCA(2)
low_d = pca.fit_transform(X)
plt.scatter(low_d[:,0], low_d[:,1])
Which produces this plot:
We clearly see two clusters, but the data were generated completely at random with no structure at all!
Normalizing changes the plot, but we still see 2 clusters:
# normalize
Xn = normalize(X)
pca = PCA(2)
low_d = pca.fit_transform(Xn)
plt.scatter(low_d[:,0], low_d[:,1])
The fact that the binary variable was on a different scale from the others has created a clustering effect where one might not necessarily exist. This is because the SVD considers it more than other variables as it contributes more to squared error. This may be solved by scaling the dataset:
# Scale
Xs = scale(X)
low_d = pca.fit_transform(Xs)
plt.scatter(low_d[:,0], low_d[:,1])
We finally see (correctly) that the data are completely random noise.
I conjecture that in your case your 0-5 variable may be dominating the 0-1 dummy variables, leading to clustering where there shouldn't be any (does it happen that the 0-5 variable accumulates on the edges of the scale?).
Edit:
I recently came across the concept of the Spatial Sign Covariance Matrix, which would appear to conduct the normalization we discussed in order to generate a robust covariance matrix. Eigenanalysis thereupon would yield a normalized PCA algorithm, which is discussed in this article. | Normalizing vs Scaling before PCA | Scaling (what I would call centering and scaling) is very important for PCA because of the way that the principal components are calculated. PCA is solved via the Singular Value Decomposition, which f | Normalizing vs Scaling before PCA
Scaling (what I would call centering and scaling) is very important for PCA because of the way that the principal components are calculated. PCA is solved via the Singular Value Decomposition, which finds linear subspaces which best represent your data in the squared sense. The two parts I've italicized are the reason that we center and scale (respectively).
Linear Subspaces are an important topic of study in Linear Algebra and the most important consequence of a linear subspace for PCA is that it has to go through the origin, the point [0, 0, ..., 0]. So if, say, you're measuring something like the GDP and population of a country, your data are likely to live very far from the origin, and be poorly approximated by any linear subspace. By centering our data, we guarantee that they exist near the origin, and it may be possible to approximate them with a low dimension linear subspace. In your case your data seem to all be positive, so they are most certainly not centered around 0 prior to preprocessing.
Here is an example of 2D a dataset far from the origin, which gets a useless first component until it is centered:
Scaling is important because SVD approximates in the sum of squares sense, so if one variable is on a different scale than another, it will dominate the PCA procedure, and the low D plot will really just be visualizing that dimension.
I will illustrate with an example in python.
Let's first set up an environment:
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale, normalize
import matplotlib.pyplot as plt
plt.ion()
# For reproducibility
np.random.seed(123)
We're going to generate data that are standard normal/uncorrelated in 4 dimensions, but with one additional variable that takes value either 0 or 5 randomly, giving a 5 dimensional dataset that we wish to visualize:
N = 200
P = 5
rho = 0.5
X = np.random.normal(size=[N,P])
X = np.append(X, 3*np.random.choice(2, size = [N,1]), axis = 1)
We will first do PCA without any preprocessing:
# No preprocessing:
pca = PCA(2)
low_d = pca.fit_transform(X)
plt.scatter(low_d[:,0], low_d[:,1])
Which produces this plot:
We clearly see two clusters, but the data were generated completely at random with no structure at all!
Normalizing changes the plot, but we still see 2 clusters:
# normalize
Xn = normalize(X)
pca = PCA(2)
low_d = pca.fit_transform(Xn)
plt.scatter(low_d[:,0], low_d[:,1])
The fact that the binary variable was on a different scale from the others has created a clustering effect where one might not necessarily exist. This is because the SVD considers it more than other variables as it contributes more to squared error. This may be solved by scaling the dataset:
# Scale
Xs = scale(X)
low_d = pca.fit_transform(Xs)
plt.scatter(low_d[:,0], low_d[:,1])
We finally see (correctly) that the data are completely random noise.
I conjecture that in your case your 0-5 variable may be dominating the 0-1 dummy variables, leading to clustering where there shouldn't be any (does it happen that the 0-5 variable accumulates on the edges of the scale?).
Edit:
I recently came across the concept of the Spatial Sign Covariance Matrix, which would appear to conduct the normalization we discussed in order to generate a robust covariance matrix. Eigenanalysis thereupon would yield a normalized PCA algorithm, which is discussed in this article. | Normalizing vs Scaling before PCA
Scaling (what I would call centering and scaling) is very important for PCA because of the way that the principal components are calculated. PCA is solved via the Singular Value Decomposition, which f |
17,494 | Normalizing vs Scaling before PCA | I'd like to point out sklearn normalize and scale use different default axes. normalize defaults to axis=1 whereas scale defaults to axis=0. Following @John Madden great example, but if we do normalization along axis=0, the two clusters will also disappear.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale, normalize
import matplotlib.pyplot as plt
# For reproducibility
np.random.seed(123)
N = 200
P = 5
rho = 0.5
X = np.random.normal(size=[N,P])
X = np.append(X, 3*np.random.choice(2, size = [N,1]), axis = 1)
X = normalize(X, axis=0)
# No preprocessing:
pca = PCA(2)
low_d = pca.fit_transform(X)
plt.scatter(low_d[:,0], low_d[:,1])
plt.show() | Normalizing vs Scaling before PCA | I'd like to point out sklearn normalize and scale use different default axes. normalize defaults to axis=1 whereas scale defaults to axis=0. Following @John Madden great example, but if we do normaliz | Normalizing vs Scaling before PCA
I'd like to point out sklearn normalize and scale use different default axes. normalize defaults to axis=1 whereas scale defaults to axis=0. Following @John Madden great example, but if we do normalization along axis=0, the two clusters will also disappear.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale, normalize
import matplotlib.pyplot as plt
# For reproducibility
np.random.seed(123)
N = 200
P = 5
rho = 0.5
X = np.random.normal(size=[N,P])
X = np.append(X, 3*np.random.choice(2, size = [N,1]), axis = 1)
X = normalize(X, axis=0)
# No preprocessing:
pca = PCA(2)
low_d = pca.fit_transform(X)
plt.scatter(low_d[:,0], low_d[:,1])
plt.show() | Normalizing vs Scaling before PCA
I'd like to point out sklearn normalize and scale use different default axes. normalize defaults to axis=1 whereas scale defaults to axis=0. Following @John Madden great example, but if we do normaliz |
17,495 | What justifies this calculation of the derivative of a matrix function? | There is a subtle but heavy abuse of the notation that renders many of the steps confusing. Let's address this issue by going back to the definitions of matrix multiplication, transposition, traces, and derivatives. For those wishing to omit the explanations, just jump to the last section "Putting It All Together" to see how short and simple a rigorous demonstration can be.
Notation and Concepts
Dimensions
For the expression $ABA^\prime C$ to make sense when $A$ is an $m\times n$ matrix, $B$ must be a (square) $n\times n$ matrix and $C$ must be an $m\times p$ matrix, whence the product is an $m\times p$ matrix. In order to take the trace (which is the sum of diagonal elements, $\operatorname{Tr}(X)=\sum_i X_{ii}$), then $p=m$, making $C$ a square matrix.
Derivatives
The notation "$\nabla_A$" appears to refer to the derivative of an expression with respect to $A$. Ordinarily, differentiation is an operation performed on functions $f:\mathbb{R}^N\to\mathbb{R}^M$. The derivative at a point $x\in \mathbb{R}^N$ is a linear transformation $Df(x):\mathbb{R}^N\to\mathbb{R}^M$. Upon choosing bases for these vector spaces, such a transformation can be represented as an $M\times N$ matrix. That is not the case here!
Matrices as vectors
Instead, $A$ is being considered as an element of $\mathbb{R}^{mn}$: its coefficients are being unrolled (usually either row by row or column by column) into a vector of length $N=mn$. The function $f(A)=\operatorname{Tr}(ABA^\prime C)$ has real values, whence $M=1$. Consequently, $Df(x)$ must be a $1\times mn$ matrix: it's a row vector representing a linear form on $\mathbb{R}^{mn}$. Howver, the calculations in the question use a different way of representing linear forms: their coefficients are rolled back up into $m\times n$ matrices.
The trace as a linear form
Let $\omega$ be a constant $m\times n$ matrix. Then, by definition of the trace and of matrix multiplication,
$$\eqalign{
\operatorname{Tr}(A\omega^\prime) &= \sum_{i=1}^m(A\omega^\prime)_{ii} = \sum_{i=1}^m\left(\sum_{j=1}^n A_{ij}(\omega^\prime)_{ji}\right) = \sum_{i,j} \omega_{ij}A_{ij}
}$$
This expresses the most general possible linear combination of the coefficients of $A$: $\omega$ is a matrix of the same shape as $A$ and its coefficient in row $i$ and column $j$ is the coefficient of $A_{ij}$ in the linear combination. Because $\omega_{ij}A_{ij}=A_{ij}\omega_{ij}$, the roles of $\omega$ and $A$ may switched, giving the equivalent expression
$$\sum_{i,j} \omega_{ij}A_{ij} = \operatorname{Tr}(A\omega^\prime) = \operatorname{Tr}(\omega A^\prime).\tag{1}$$
By identifying a constant matrix $\omega$ with either of the functions $A\to \operatorname{Tr}(A \omega^\prime)$ or $A\to \operatorname{Tr}(\omega A^\prime)$, we may represent linear forms on the space of $m\times n$ matrices as $m\times n$ matrices. (Do not confuse these with derivatives of functions from $\mathbb{R}^n$ to $\mathbb{R}^m$!)
Computing a Derivative
The definition
Derivatives of many of the matrix functions encountered in statistics are most easily and reliably computed from the definition: you don't really need to resort to complicated rules of matrix differentiation. This definition says that $f$ is differentiable at $x$ if and only if there is a linear transformation $L$ such that
$$f(x+h) - f(x) = Lh + o(|h|)$$
for arbitrarily small displacements $h\in \mathbb{R}^N$. The little-oh notation means that the error made in approximating the difference $f(x+h)-f(x)$ by $Lh$ is arbitrarily smaller than the size of $h$ for sufficiently small $h$. In particular, we may always ignore errors that are proportional to $|h|^2$.
The calculation
Let's apply the definition to the function in question. Multiplying, expanding, and ignoring the term with a product of two $h$'s in it,
$$\eqalign{
f(A+h)-f(A) &= \operatorname{Tr}((A+h)B(A+h)^\prime C) - \operatorname{Tr}(ABA^\prime C) \\
&= \operatorname{Tr}(hBA^\prime C) +\operatorname{Tr}(ABh^\prime C) + o(|h|).\tag{2}
}$$
To identify the derivative $L=Df(A)$, we must get this into the form $(1)$. The first term on the right is already in this form, with $\omega^\prime = BA^\prime C$. The other term on the right has the form $\operatorname{Tr}(Xh^\prime C)$ for $X=AB$. Let's write this out:
$$\operatorname{Tr}(Xh^\prime C) = \sum_{i=1}^m\sum_{j=1}^n\sum_{k=1}^m X_{ij} h_{kj} C_{ki} = \sum_{i,j,k}h_{kj} \left(C_{ki}X_{ij}\right) =\operatorname{Tr}((CX)h^\prime).\tag{3}$$
Recalling $X=AB$, $(2)$ can be rewritten
$$f(A+h) - f(A) = \operatorname{Tr}(h\, BA^\prime C\,) + \operatorname{Tr}(CAB\, h^\prime\,)+o(|h|).$$
It is in this sense that we may consider the derivative of $f$ at $A$ to be $$Df(A) = (BA^\prime C)^\prime + CAB = C^\prime A B^\prime + CAB,$$ because these matrices play the roles of $\omega$ in the trace formulas $(1)$.
Putting It All Together
Here, then, is a complete solution.
Let $A$ be an $m\times n$ matrix, $B$ an $n\times n$ matrix, and $C$ an $m\times m$ matrix. Let $f(A) = \operatorname{Tr}(ABA^\prime C)$. Let $h$ be an $m\times n$ matrix with arbitrarily small coefficients. Because (by identity $(3)$) $$\eqalign{f(A+h) - f(A) &= \operatorname{Tr}(hBA^\prime C) +\operatorname{Tr}(ABh^\prime C) + o(|h|) \\
&=\operatorname{Tr}(h(C^\prime A B^\prime)^\prime + (CAB)h^\prime) + o(|h|),}$$ $f$ is differentiable and its derivative is the linear form determined by the matrix $$C^\prime A B^\prime + CAB.$$
Because this takes only about half the work and involves only the most basic manipulations of matrices and traces (multiplication and transposition), it has to be considered a simpler--and arguably more perspicuous--demonstration of the result. If you really want to understand the individual steps in the original demonstration, you might find it fruitful to compare them to the calculations shown here. | What justifies this calculation of the derivative of a matrix function? | There is a subtle but heavy abuse of the notation that renders many of the steps confusing. Let's address this issue by going back to the definitions of matrix multiplication, transposition, traces, | What justifies this calculation of the derivative of a matrix function?
There is a subtle but heavy abuse of the notation that renders many of the steps confusing. Let's address this issue by going back to the definitions of matrix multiplication, transposition, traces, and derivatives. For those wishing to omit the explanations, just jump to the last section "Putting It All Together" to see how short and simple a rigorous demonstration can be.
Notation and Concepts
Dimensions
For the expression $ABA^\prime C$ to make sense when $A$ is an $m\times n$ matrix, $B$ must be a (square) $n\times n$ matrix and $C$ must be an $m\times p$ matrix, whence the product is an $m\times p$ matrix. In order to take the trace (which is the sum of diagonal elements, $\operatorname{Tr}(X)=\sum_i X_{ii}$), then $p=m$, making $C$ a square matrix.
Derivatives
The notation "$\nabla_A$" appears to refer to the derivative of an expression with respect to $A$. Ordinarily, differentiation is an operation performed on functions $f:\mathbb{R}^N\to\mathbb{R}^M$. The derivative at a point $x\in \mathbb{R}^N$ is a linear transformation $Df(x):\mathbb{R}^N\to\mathbb{R}^M$. Upon choosing bases for these vector spaces, such a transformation can be represented as an $M\times N$ matrix. That is not the case here!
Matrices as vectors
Instead, $A$ is being considered as an element of $\mathbb{R}^{mn}$: its coefficients are being unrolled (usually either row by row or column by column) into a vector of length $N=mn$. The function $f(A)=\operatorname{Tr}(ABA^\prime C)$ has real values, whence $M=1$. Consequently, $Df(x)$ must be a $1\times mn$ matrix: it's a row vector representing a linear form on $\mathbb{R}^{mn}$. Howver, the calculations in the question use a different way of representing linear forms: their coefficients are rolled back up into $m\times n$ matrices.
The trace as a linear form
Let $\omega$ be a constant $m\times n$ matrix. Then, by definition of the trace and of matrix multiplication,
$$\eqalign{
\operatorname{Tr}(A\omega^\prime) &= \sum_{i=1}^m(A\omega^\prime)_{ii} = \sum_{i=1}^m\left(\sum_{j=1}^n A_{ij}(\omega^\prime)_{ji}\right) = \sum_{i,j} \omega_{ij}A_{ij}
}$$
This expresses the most general possible linear combination of the coefficients of $A$: $\omega$ is a matrix of the same shape as $A$ and its coefficient in row $i$ and column $j$ is the coefficient of $A_{ij}$ in the linear combination. Because $\omega_{ij}A_{ij}=A_{ij}\omega_{ij}$, the roles of $\omega$ and $A$ may switched, giving the equivalent expression
$$\sum_{i,j} \omega_{ij}A_{ij} = \operatorname{Tr}(A\omega^\prime) = \operatorname{Tr}(\omega A^\prime).\tag{1}$$
By identifying a constant matrix $\omega$ with either of the functions $A\to \operatorname{Tr}(A \omega^\prime)$ or $A\to \operatorname{Tr}(\omega A^\prime)$, we may represent linear forms on the space of $m\times n$ matrices as $m\times n$ matrices. (Do not confuse these with derivatives of functions from $\mathbb{R}^n$ to $\mathbb{R}^m$!)
Computing a Derivative
The definition
Derivatives of many of the matrix functions encountered in statistics are most easily and reliably computed from the definition: you don't really need to resort to complicated rules of matrix differentiation. This definition says that $f$ is differentiable at $x$ if and only if there is a linear transformation $L$ such that
$$f(x+h) - f(x) = Lh + o(|h|)$$
for arbitrarily small displacements $h\in \mathbb{R}^N$. The little-oh notation means that the error made in approximating the difference $f(x+h)-f(x)$ by $Lh$ is arbitrarily smaller than the size of $h$ for sufficiently small $h$. In particular, we may always ignore errors that are proportional to $|h|^2$.
The calculation
Let's apply the definition to the function in question. Multiplying, expanding, and ignoring the term with a product of two $h$'s in it,
$$\eqalign{
f(A+h)-f(A) &= \operatorname{Tr}((A+h)B(A+h)^\prime C) - \operatorname{Tr}(ABA^\prime C) \\
&= \operatorname{Tr}(hBA^\prime C) +\operatorname{Tr}(ABh^\prime C) + o(|h|).\tag{2}
}$$
To identify the derivative $L=Df(A)$, we must get this into the form $(1)$. The first term on the right is already in this form, with $\omega^\prime = BA^\prime C$. The other term on the right has the form $\operatorname{Tr}(Xh^\prime C)$ for $X=AB$. Let's write this out:
$$\operatorname{Tr}(Xh^\prime C) = \sum_{i=1}^m\sum_{j=1}^n\sum_{k=1}^m X_{ij} h_{kj} C_{ki} = \sum_{i,j,k}h_{kj} \left(C_{ki}X_{ij}\right) =\operatorname{Tr}((CX)h^\prime).\tag{3}$$
Recalling $X=AB$, $(2)$ can be rewritten
$$f(A+h) - f(A) = \operatorname{Tr}(h\, BA^\prime C\,) + \operatorname{Tr}(CAB\, h^\prime\,)+o(|h|).$$
It is in this sense that we may consider the derivative of $f$ at $A$ to be $$Df(A) = (BA^\prime C)^\prime + CAB = C^\prime A B^\prime + CAB,$$ because these matrices play the roles of $\omega$ in the trace formulas $(1)$.
Putting It All Together
Here, then, is a complete solution.
Let $A$ be an $m\times n$ matrix, $B$ an $n\times n$ matrix, and $C$ an $m\times m$ matrix. Let $f(A) = \operatorname{Tr}(ABA^\prime C)$. Let $h$ be an $m\times n$ matrix with arbitrarily small coefficients. Because (by identity $(3)$) $$\eqalign{f(A+h) - f(A) &= \operatorname{Tr}(hBA^\prime C) +\operatorname{Tr}(ABh^\prime C) + o(|h|) \\
&=\operatorname{Tr}(h(C^\prime A B^\prime)^\prime + (CAB)h^\prime) + o(|h|),}$$ $f$ is differentiable and its derivative is the linear form determined by the matrix $$C^\prime A B^\prime + CAB.$$
Because this takes only about half the work and involves only the most basic manipulations of matrices and traces (multiplication and transposition), it has to be considered a simpler--and arguably more perspicuous--demonstration of the result. If you really want to understand the individual steps in the original demonstration, you might find it fruitful to compare them to the calculations shown here. | What justifies this calculation of the derivative of a matrix function?
There is a subtle but heavy abuse of the notation that renders many of the steps confusing. Let's address this issue by going back to the definitions of matrix multiplication, transposition, traces, |
17,496 | What justifies this calculation of the derivative of a matrix function? | There are some special matrix notations in machine learning community, which are implicit by experts but often confuse new practitioners. Some of such notations are described briefly in page 698 of "Pattern Recognition and Machine Learning" by Christopher M. Bishop. So, your life will be easier if you are familiar with that page.
If we have a scalar function (e.g., trace) of a matrix, $f(\mathbf A)$, where $\mathbf A=(A_{ij})$, you can take derivative with regard to element $A_{ij}$: $$\frac{\partial f(\mathbf A)}{\partial A_{ij}}.$$
This is well defined in any calculus text. But in machine learning community, people assembly these simple derivatives into a matrix, or "write this
result more compactly" as said by Bishop's book:
$$\frac{\partial f(\mathbf A)}{\partial\mathbf A}=\left(\frac{\partial f(\mathbf A)}{\partial A_{ij}}\right).$$
People who knows Matrix calculus would recall that this is a so-called denominator layout notation. But as that wikipage says, machine learning community does not follow a single layout for different derivative types. So, it is wise to figure out what layout the author is following before assuming something. At least Andrew Ng is following denominator layout notation for scalar-by-matrix derivatives.
Let me start by citing simple product rule of derivative $$\bigl(f(x)g(x)\bigr)'=f'(x)\color{green}{g(x)}+\color{green}{f(x)}g'(x).$$ This rule means that by taking derivative, a single product becomes a sum of two products, with one factor being further derived but another factor being considered a constant which I marked in a relieving color of green.
Now let's think of trace of the product of two matrices. Here the two matrices are general; their product does not have to be square. Yes, this is the way things are in machine learning community. Trace is the sum of leading diagonal, but unsquared matrices have no problem having a leading diagonal (see here).
Now let's think that the elements of the above two matrices are all functions of $A_{ij}$, and next take derivative of the trace of the multiplication of two matrices w.r.t. $A_{ij}$. Only one summand of the trace is involved, right? That single summand comes from one row of the left matrix and one column of the right matrix, again a sum of products, right? Each summand of such a sum has a form of $f(A_{ij})g(A_{ij})$, so if we take the derivative, it splits into a sum of two products:
$$f'(A_{ij})\color{green}{g(A_{ij})}+\color{green}{f(A_{ij})}g'(A_{ij}),$$
where the green part is considered a constant.
Now let's expand the above to matrix form because the same thing happens for all $A_{ij}$'s. We have
$$\eqalign{
\frac{\partial\operatorname{Tr}\bigl(f(\mathbf A)g(\mathbf A)\bigr)}{\partial\mathbf A}&=\operatorname{Tr}\bigl(\frac{f(\mathbf A)}{\partial\mathbf A}\color{green}{g(\mathbf A)}+\color{green}{f(\mathbf A)}\frac{\partial g(\mathbf A)}{\partial\mathbf A}\bigr)\\
&=\frac{\partial\operatorname{Tr}\bigl(f(\mathbf A)\color{green}{g(\mathbf A)}\bigr)}{\partial\mathbf A}+\frac{\partial\operatorname{Tr}\bigl(\color{green}{f(\mathbf A)}g(\mathbf A)\bigr)}{\partial\mathbf A},
}$$
where the green parts at the right hand are regarded as constant matrix. Here I used the fact $\operatorname{Tr}(\mathbf A_1+\mathbf A_2)=\operatorname{Tr}\mathbf A_1+\operatorname{Tr}\mathbf A_2$ and linearity of derivative so $\partial\mathbf A$ can penetrate $\operatorname{Tr}$. This step requires some math thinking capability. I hope you can get through it.
Plugging $f(\mathbf A)=\mathbf A\mathbf B$ and $g(\mathbf A)=\mathbf A^T\mathbf C$, we get the second equation. The circle $\circ$ represents matrix $\mathbf A$ in Andrew Ng's derivation. The following derivation is easier because of established identities in page 698 of Bishop's book.
Now we have that the original derivative is equal to $$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\mathbf B\color{green}{\mathbf A^T\mathbf C})+\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\mathbf C).$$ Since matrix $\mathbf B$ and $\mathbf C$ are constant too w.r.t. elements $A_{ij}$ and hence w.r.t. matrix $\mathbf A$, we color them in green as well:
$$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\color{green}{\mathbf B\mathbf A^T\mathbf C})+\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C}).\tag{1}$$
Now we advance to the third equality of Andrew Ng's derivation of derivative. The first term of the above result (1) turns into $(\color{green}{\mathbf B\mathbf A^T\mathbf C})^T=\mathbf C^T\mathbf A\mathbf B^T$, according to identity (C.24) in page 698 of Bishop's book:
$$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\color{green}{\mathbf B})=\color{green}{\mathbf B}^T.\tag{C.24}$$
Now you should know why I tirelessly mark constant matrix as green. The first term in the third equation of Andrew Ng's derivation is confusing in that he missed the trace. I am really a bit tired at this point. Take a break of typing, but you keep on reading.
The second term contains a transpose of $\mathbf A$. We want to take the derivative w.r.t. this transpose $\mathbf A^T$ to take advantage of identity (C.24). To that end, remember we use denominator layout to arrange partial derivatives in the resulting derivative matrix. If the variable matrix is $\mathbf A^T$, the denominator layout will result in nothing but a transpose of the matrix $\frac{\partial}{\partial\mathbf A}$. So, we have
$$\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})=\left(\frac{\partial}{\partial\mathbf A}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})\right)^T,$$
which leads to the second term of the third equality.
In order to derive $\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})$ based on identity (C.24) where the variable matrix is the left matrix of the multiplication, we apply the cyclic property of trace to deduce $\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})=\operatorname{Tr}(\mathbf A^T\color{green}{\mathbf C\mathbf A\mathbf B}).$ In the second term of the fourth equality, Andrew Ng wrote $Cf(A)$ out of the $\operatorname{Tr}$ operator. I think that's a typo.
Now it is easy to apply Bishop's identity (C.24) to obtain
$$\eqalign{
\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})
&=\left(\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})\right)^T\\
&=\left(\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\mathbf A^T\color{green}{\mathbf C\mathbf A\mathbf B})\right)^T\\
&=\bigl((\color{green}{\mathbf C\mathbf A\mathbf B})^T\bigr)^T\\
&=\mathbf C\mathbf A\mathbf B.}$$
We have proved that the first term of (1) equals $\mathbf C^T\mathbf A\mathbf B^T$. Above we get the second term $\mathbf C\mathbf A\mathbf B$. Now we can conclude the whole proof by combining them as the final result of the derivative: $\mathbf C^T\mathbf A\mathbf B^T+\mathbf C\mathbf A\mathbf B$. | What justifies this calculation of the derivative of a matrix function? | There are some special matrix notations in machine learning community, which are implicit by experts but often confuse new practitioners. Some of such notations are described briefly in page 698 of "P | What justifies this calculation of the derivative of a matrix function?
There are some special matrix notations in machine learning community, which are implicit by experts but often confuse new practitioners. Some of such notations are described briefly in page 698 of "Pattern Recognition and Machine Learning" by Christopher M. Bishop. So, your life will be easier if you are familiar with that page.
If we have a scalar function (e.g., trace) of a matrix, $f(\mathbf A)$, where $\mathbf A=(A_{ij})$, you can take derivative with regard to element $A_{ij}$: $$\frac{\partial f(\mathbf A)}{\partial A_{ij}}.$$
This is well defined in any calculus text. But in machine learning community, people assembly these simple derivatives into a matrix, or "write this
result more compactly" as said by Bishop's book:
$$\frac{\partial f(\mathbf A)}{\partial\mathbf A}=\left(\frac{\partial f(\mathbf A)}{\partial A_{ij}}\right).$$
People who knows Matrix calculus would recall that this is a so-called denominator layout notation. But as that wikipage says, machine learning community does not follow a single layout for different derivative types. So, it is wise to figure out what layout the author is following before assuming something. At least Andrew Ng is following denominator layout notation for scalar-by-matrix derivatives.
Let me start by citing simple product rule of derivative $$\bigl(f(x)g(x)\bigr)'=f'(x)\color{green}{g(x)}+\color{green}{f(x)}g'(x).$$ This rule means that by taking derivative, a single product becomes a sum of two products, with one factor being further derived but another factor being considered a constant which I marked in a relieving color of green.
Now let's think of trace of the product of two matrices. Here the two matrices are general; their product does not have to be square. Yes, this is the way things are in machine learning community. Trace is the sum of leading diagonal, but unsquared matrices have no problem having a leading diagonal (see here).
Now let's think that the elements of the above two matrices are all functions of $A_{ij}$, and next take derivative of the trace of the multiplication of two matrices w.r.t. $A_{ij}$. Only one summand of the trace is involved, right? That single summand comes from one row of the left matrix and one column of the right matrix, again a sum of products, right? Each summand of such a sum has a form of $f(A_{ij})g(A_{ij})$, so if we take the derivative, it splits into a sum of two products:
$$f'(A_{ij})\color{green}{g(A_{ij})}+\color{green}{f(A_{ij})}g'(A_{ij}),$$
where the green part is considered a constant.
Now let's expand the above to matrix form because the same thing happens for all $A_{ij}$'s. We have
$$\eqalign{
\frac{\partial\operatorname{Tr}\bigl(f(\mathbf A)g(\mathbf A)\bigr)}{\partial\mathbf A}&=\operatorname{Tr}\bigl(\frac{f(\mathbf A)}{\partial\mathbf A}\color{green}{g(\mathbf A)}+\color{green}{f(\mathbf A)}\frac{\partial g(\mathbf A)}{\partial\mathbf A}\bigr)\\
&=\frac{\partial\operatorname{Tr}\bigl(f(\mathbf A)\color{green}{g(\mathbf A)}\bigr)}{\partial\mathbf A}+\frac{\partial\operatorname{Tr}\bigl(\color{green}{f(\mathbf A)}g(\mathbf A)\bigr)}{\partial\mathbf A},
}$$
where the green parts at the right hand are regarded as constant matrix. Here I used the fact $\operatorname{Tr}(\mathbf A_1+\mathbf A_2)=\operatorname{Tr}\mathbf A_1+\operatorname{Tr}\mathbf A_2$ and linearity of derivative so $\partial\mathbf A$ can penetrate $\operatorname{Tr}$. This step requires some math thinking capability. I hope you can get through it.
Plugging $f(\mathbf A)=\mathbf A\mathbf B$ and $g(\mathbf A)=\mathbf A^T\mathbf C$, we get the second equation. The circle $\circ$ represents matrix $\mathbf A$ in Andrew Ng's derivation. The following derivation is easier because of established identities in page 698 of Bishop's book.
Now we have that the original derivative is equal to $$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\mathbf B\color{green}{\mathbf A^T\mathbf C})+\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\mathbf C).$$ Since matrix $\mathbf B$ and $\mathbf C$ are constant too w.r.t. elements $A_{ij}$ and hence w.r.t. matrix $\mathbf A$, we color them in green as well:
$$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\color{green}{\mathbf B\mathbf A^T\mathbf C})+\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C}).\tag{1}$$
Now we advance to the third equality of Andrew Ng's derivation of derivative. The first term of the above result (1) turns into $(\color{green}{\mathbf B\mathbf A^T\mathbf C})^T=\mathbf C^T\mathbf A\mathbf B^T$, according to identity (C.24) in page 698 of Bishop's book:
$$\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\mathbf A\color{green}{\mathbf B})=\color{green}{\mathbf B}^T.\tag{C.24}$$
Now you should know why I tirelessly mark constant matrix as green. The first term in the third equation of Andrew Ng's derivation is confusing in that he missed the trace. I am really a bit tired at this point. Take a break of typing, but you keep on reading.
The second term contains a transpose of $\mathbf A$. We want to take the derivative w.r.t. this transpose $\mathbf A^T$ to take advantage of identity (C.24). To that end, remember we use denominator layout to arrange partial derivatives in the resulting derivative matrix. If the variable matrix is $\mathbf A^T$, the denominator layout will result in nothing but a transpose of the matrix $\frac{\partial}{\partial\mathbf A}$. So, we have
$$\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})=\left(\frac{\partial}{\partial\mathbf A}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})\right)^T,$$
which leads to the second term of the third equality.
In order to derive $\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})$ based on identity (C.24) where the variable matrix is the left matrix of the multiplication, we apply the cyclic property of trace to deduce $\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})=\operatorname{Tr}(\mathbf A^T\color{green}{\mathbf C\mathbf A\mathbf B}).$ In the second term of the fourth equality, Andrew Ng wrote $Cf(A)$ out of the $\operatorname{Tr}$ operator. I think that's a typo.
Now it is easy to apply Bishop's identity (C.24) to obtain
$$\eqalign{
\frac{\partial}{\partial\mathbf A}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})
&=\left(\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\color{green}{\mathbf A\mathbf B}\mathbf A^T\color{green}{\mathbf C})\right)^T\\
&=\left(\frac{\partial}{\partial\mathbf A^T}\operatorname{Tr}(\mathbf A^T\color{green}{\mathbf C\mathbf A\mathbf B})\right)^T\\
&=\bigl((\color{green}{\mathbf C\mathbf A\mathbf B})^T\bigr)^T\\
&=\mathbf C\mathbf A\mathbf B.}$$
We have proved that the first term of (1) equals $\mathbf C^T\mathbf A\mathbf B^T$. Above we get the second term $\mathbf C\mathbf A\mathbf B$. Now we can conclude the whole proof by combining them as the final result of the derivative: $\mathbf C^T\mathbf A\mathbf B^T+\mathbf C\mathbf A\mathbf B$. | What justifies this calculation of the derivative of a matrix function?
There are some special matrix notations in machine learning community, which are implicit by experts but often confuse new practitioners. Some of such notations are described briefly in page 698 of "P |
17,497 | Feature selection using deep learning? | One approach you can take for almost any prediction model is to first train your model and find its accuracy, then for one input add some noise to it and check the accuracy again. Repeat this for each input and observe how the noise worsens the predictions. If an input is important then the extra uncertainty due to the noise will be detrimental.
Remember set the variance of the noise to be proportional to the variance of the input in question.
Of course noise is random and you don't want one input to appear unimportant due to random effects. If you have few training examples then consider repeatedly calculating the change in accuracy for each training example with a new noise added each time.
In response to the comments:
This analysis can also be done by removing a variable entirely but this has some downsides compared to adding noise.
Suppose that one of your inputs is constant, it acts like a bias term so it has some role to play in the prediction but it adds no information. If you removed this input entirely then the prediction would become less accurate because the perceptrons are getting the wrong bias. This makes the input look like it is important for prediction even though it adds no information. Adding noise won't cause this problem. This first point isn't a problem if you have standardized all inputs to have zero mean.
If two inputs are correlated then the the information about one input gives information about the other. A model could be trained well if you used only one of the correlated inputs so you want the analysis to find that one input isn't helpful. If you just removed one of the inputs then, like the first point made, the prediction accuracy would decrease a lot which indicates that it is important. However, adding noise won't cause this problem. | Feature selection using deep learning? | One approach you can take for almost any prediction model is to first train your model and find its accuracy, then for one input add some noise to it and check the accuracy again. Repeat this for each | Feature selection using deep learning?
One approach you can take for almost any prediction model is to first train your model and find its accuracy, then for one input add some noise to it and check the accuracy again. Repeat this for each input and observe how the noise worsens the predictions. If an input is important then the extra uncertainty due to the noise will be detrimental.
Remember set the variance of the noise to be proportional to the variance of the input in question.
Of course noise is random and you don't want one input to appear unimportant due to random effects. If you have few training examples then consider repeatedly calculating the change in accuracy for each training example with a new noise added each time.
In response to the comments:
This analysis can also be done by removing a variable entirely but this has some downsides compared to adding noise.
Suppose that one of your inputs is constant, it acts like a bias term so it has some role to play in the prediction but it adds no information. If you removed this input entirely then the prediction would become less accurate because the perceptrons are getting the wrong bias. This makes the input look like it is important for prediction even though it adds no information. Adding noise won't cause this problem. This first point isn't a problem if you have standardized all inputs to have zero mean.
If two inputs are correlated then the the information about one input gives information about the other. A model could be trained well if you used only one of the correlated inputs so you want the analysis to find that one input isn't helpful. If you just removed one of the inputs then, like the first point made, the prediction accuracy would decrease a lot which indicates that it is important. However, adding noise won't cause this problem. | Feature selection using deep learning?
One approach you can take for almost any prediction model is to first train your model and find its accuracy, then for one input add some noise to it and check the accuracy again. Repeat this for each |
17,498 | Feature selection using deep learning? | Maybe check this paper: https://arxiv.org/pdf/1712.08645.pdf
They use dropout to rank features.
... In this work we use the Dropout concept on the input feature layer and optimize the corresponding feature-wise dropout rate. Since each feature is removed stochastically, our method creates a similar effect to feature bagging (Ho, 1995) and manages to rank correlated features better than other non-bagging methods such as LASSO. We compare our method to Random Forest (RF), LASSO,
ElasticNet, Marginal ranking and several techniques to derive importance
in DNN such as Deep Feature Selection and various heuristics... | Feature selection using deep learning? | Maybe check this paper: https://arxiv.org/pdf/1712.08645.pdf
They use dropout to rank features.
... In this work we use the Dropout concept on the input feature layer and optimize the corresponding f | Feature selection using deep learning?
Maybe check this paper: https://arxiv.org/pdf/1712.08645.pdf
They use dropout to rank features.
... In this work we use the Dropout concept on the input feature layer and optimize the corresponding feature-wise dropout rate. Since each feature is removed stochastically, our method creates a similar effect to feature bagging (Ho, 1995) and manages to rank correlated features better than other non-bagging methods such as LASSO. We compare our method to Random Forest (RF), LASSO,
ElasticNet, Marginal ranking and several techniques to derive importance
in DNN such as Deep Feature Selection and various heuristics... | Feature selection using deep learning?
Maybe check this paper: https://arxiv.org/pdf/1712.08645.pdf
They use dropout to rank features.
... In this work we use the Dropout concept on the input feature layer and optimize the corresponding f |
17,499 | Feature selection using deep learning? | Have a look at this post:
https://medium.com/@a.mirzaei69/how-to-use-deep-learning-for-feature-selection-python-keras-24a68bef1e33
and this paper:
https://arxiv.org/pdf/1903.07045.pdf
They present a nice scheme for applying deep models for feature selection. | Feature selection using deep learning? | Have a look at this post:
https://medium.com/@a.mirzaei69/how-to-use-deep-learning-for-feature-selection-python-keras-24a68bef1e33
and this paper:
https://arxiv.org/pdf/1903.07045.pdf
They present a n | Feature selection using deep learning?
Have a look at this post:
https://medium.com/@a.mirzaei69/how-to-use-deep-learning-for-feature-selection-python-keras-24a68bef1e33
and this paper:
https://arxiv.org/pdf/1903.07045.pdf
They present a nice scheme for applying deep models for feature selection. | Feature selection using deep learning?
Have a look at this post:
https://medium.com/@a.mirzaei69/how-to-use-deep-learning-for-feature-selection-python-keras-24a68bef1e33
and this paper:
https://arxiv.org/pdf/1903.07045.pdf
They present a n |
17,500 | Difference between one-way and two-way fixed effects, and their estimation | The unobserved effects model is modeled as:
\begin{equation}
y = X\beta + u
\end{equation}
where
\begin{equation}
u = c_{i} + \lambda_{t} + v_{it}
\end{equation}
A one-way error model assumes $\lambda_{t} = 0$ while a two-way error allows for $\lambda \in \mathbb{R}$ and that is the answer to the first question.
The second question cannot be answered without more assumptions about the error structure or purpose of the study. Using Wooldridge (2010) chapters 10 and 11, generalize each of the assumptions to cover the temporal error structure as well. For example, when considering POLS, the critical assumption is $\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}u\right) = 0$. In the chapter it is summarized as meeting the following conditions:
$\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}c\right) = 0$
$\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}v\right) = 0$
However, if one does not assume $\lambda_{t} = 0$, i.e., two-way error model, a third condition must be satisfied for consistency of the POLS estimator:
\begin{equation}
\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}\lambda\right) = 0
\end{equation}
and so on.
In the case of estimating the fixed effects, one can go with LSDV (including indicators for the panel ID and temporal ID), but the dimension might become unfeasible fast. One alternative is to use the one-way error within estimator and include the time dummies such as one usually do with software that does not allow for two-way error models like Stata. A third and most efficient way is to estimate it with the two-way error within estimator.
\begin{equation}
y_{it} − \bar{y}_{i.} − \bar{y}_{.t} + \bar{y}_{..} = (x_{it} − \bar{x}_{i.} − \bar{x}_{.t} + \bar{x}_{..})\beta
\end{equation}
This approach is coded in several statistical packages such as the R package plm and correctly adjust the degrees of freedom to include the T - 1 additional parameters compared to the one-way error within estimator.
Most two-error way model estimators are not limited to balanced panels (only a handful). For short-panels running the one-way error within estimator with time dummies is feasible. As a side note, even if one gets the estimates for the temporal effects it is important to notice that as with the LSDV fixed effects for one-way error models these are not consistent as the estimates increase in number and length of panels.
I recommend Baltagi (2013) textbook for a pretty comprehensive explanation of the estimators for one-way and two-way error models.
References:
Baltagi, Badi H. 2013. Econometric analysis of panel data. Fifth Edition. Chichester, West Sussex: John Wiley & Sons, Inc. isbn: 978-1-118-67232-7.
Croissant, Yves, and Giovanni Millo. 2008. “Panel Data Econometrics in R : The plm Package.” Journal of Statistical Software 27 (2). doi:10.18637/jss.v027.i02.
StataCorp. 2017. Stata 15 Base Reference Manual. College Station, TX: Stata Press.
Wooldridge, Jeffrey M. 2010. Econometric Analysis of Cross Section and Panel Data. Kindle Edition. The MIT Press. ISBN: 978-0-262-23258-8. | Difference between one-way and two-way fixed effects, and their estimation | The unobserved effects model is modeled as:
\begin{equation}
y = X\beta + u
\end{equation}
where
\begin{equation}
u = c_{i} + \lambda_{t} + v_{it}
\end{equation}
A one-way error model assumes $\lambda | Difference between one-way and two-way fixed effects, and their estimation
The unobserved effects model is modeled as:
\begin{equation}
y = X\beta + u
\end{equation}
where
\begin{equation}
u = c_{i} + \lambda_{t} + v_{it}
\end{equation}
A one-way error model assumes $\lambda_{t} = 0$ while a two-way error allows for $\lambda \in \mathbb{R}$ and that is the answer to the first question.
The second question cannot be answered without more assumptions about the error structure or purpose of the study. Using Wooldridge (2010) chapters 10 and 11, generalize each of the assumptions to cover the temporal error structure as well. For example, when considering POLS, the critical assumption is $\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}u\right) = 0$. In the chapter it is summarized as meeting the following conditions:
$\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}c\right) = 0$
$\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}v\right) = 0$
However, if one does not assume $\lambda_{t} = 0$, i.e., two-way error model, a third condition must be satisfied for consistency of the POLS estimator:
\begin{equation}
\mathop{\mathbb{E}}\left(\mathbf{x}_{it}^{\prime}\lambda\right) = 0
\end{equation}
and so on.
In the case of estimating the fixed effects, one can go with LSDV (including indicators for the panel ID and temporal ID), but the dimension might become unfeasible fast. One alternative is to use the one-way error within estimator and include the time dummies such as one usually do with software that does not allow for two-way error models like Stata. A third and most efficient way is to estimate it with the two-way error within estimator.
\begin{equation}
y_{it} − \bar{y}_{i.} − \bar{y}_{.t} + \bar{y}_{..} = (x_{it} − \bar{x}_{i.} − \bar{x}_{.t} + \bar{x}_{..})\beta
\end{equation}
This approach is coded in several statistical packages such as the R package plm and correctly adjust the degrees of freedom to include the T - 1 additional parameters compared to the one-way error within estimator.
Most two-error way model estimators are not limited to balanced panels (only a handful). For short-panels running the one-way error within estimator with time dummies is feasible. As a side note, even if one gets the estimates for the temporal effects it is important to notice that as with the LSDV fixed effects for one-way error models these are not consistent as the estimates increase in number and length of panels.
I recommend Baltagi (2013) textbook for a pretty comprehensive explanation of the estimators for one-way and two-way error models.
References:
Baltagi, Badi H. 2013. Econometric analysis of panel data. Fifth Edition. Chichester, West Sussex: John Wiley & Sons, Inc. isbn: 978-1-118-67232-7.
Croissant, Yves, and Giovanni Millo. 2008. “Panel Data Econometrics in R : The plm Package.” Journal of Statistical Software 27 (2). doi:10.18637/jss.v027.i02.
StataCorp. 2017. Stata 15 Base Reference Manual. College Station, TX: Stata Press.
Wooldridge, Jeffrey M. 2010. Econometric Analysis of Cross Section and Panel Data. Kindle Edition. The MIT Press. ISBN: 978-0-262-23258-8. | Difference between one-way and two-way fixed effects, and their estimation
The unobserved effects model is modeled as:
\begin{equation}
y = X\beta + u
\end{equation}
where
\begin{equation}
u = c_{i} + \lambda_{t} + v_{it}
\end{equation}
A one-way error model assumes $\lambda |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.