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
13,001
How to smooth data and force monotonicity
The recent scam package by Natalya Pya and based on the paper "Shape constrained additive models" by Pya & Wood (2015) can make part of the process mentioned in Gavin's excellent answer much easier. library(scam) con <- scam(y ~ s(x, k = k, bs = "mpd"), data = df) plot(con) There are a number of bs functions you can use - in the above I used mpd for "monotonic decreasing P-spline" but it also has functions that enforce convexity or concavity either separately or alongside the monotonic constraints.
How to smooth data and force monotonicity
The recent scam package by Natalya Pya and based on the paper "Shape constrained additive models" by Pya & Wood (2015) can make part of the process mentioned in Gavin's excellent answer much easier. l
How to smooth data and force monotonicity The recent scam package by Natalya Pya and based on the paper "Shape constrained additive models" by Pya & Wood (2015) can make part of the process mentioned in Gavin's excellent answer much easier. library(scam) con <- scam(y ~ s(x, k = k, bs = "mpd"), data = df) plot(con) There are a number of bs functions you can use - in the above I used mpd for "monotonic decreasing P-spline" but it also has functions that enforce convexity or concavity either separately or alongside the monotonic constraints.
How to smooth data and force monotonicity The recent scam package by Natalya Pya and based on the paper "Shape constrained additive models" by Pya & Wood (2015) can make part of the process mentioned in Gavin's excellent answer much easier. l
13,002
Weighted principal components analysis
It depends on what exactly your weights apply to. Row weights Let $\mathbf{X}$ be the data matrix with variables in columns and $n$ observations $\mathbf x_i$ in rows. If each observation has an associated weight $w_i$, then it is indeed straightforward to incorporate these weights into PCA. First, one needs to compute the weighted mean $\boldsymbol \mu = \frac{1}{\sum w_i}\sum w_i \mathbf x_i$ and subtract it from the data in order to center it. Then we compute the weighted covariance matrix $\frac{1}{\sum w_i}\mathbf X^\top \mathbf W \mathbf X$, where $\mathbf W = \operatorname{diag}(w_i)$ is the diagonal matrix of weights, and apply standard PCA to analyze it. Cell weights The paper by Tamuz et al., 2013, that you found, considers a more complicated case when different weights $w_{ij}$ are applied to each element of the data matrix. Then indeed there is no analytical solution and one has to use an iterative method. Note that, as acknowledged by the authors, they reinvented the wheel, as such general weights have certainly been considered before, e.g. in Gabriel and Zamir, 1979, Lower Rank Approximation of Matrices by Least Squares With Any Choice of Weights. This was also discussed here. As an additional remark: if the weights $w_{ij}$ vary with both variables and observations, but are symmetric, so that $w_{ij}=w_{ji}$, then analytic solution is possible again, see Koren and Carmel, 2004, Robust Linear Dimensionality Reduction.
Weighted principal components analysis
It depends on what exactly your weights apply to. Row weights Let $\mathbf{X}$ be the data matrix with variables in columns and $n$ observations $\mathbf x_i$ in rows. If each observation has an assoc
Weighted principal components analysis It depends on what exactly your weights apply to. Row weights Let $\mathbf{X}$ be the data matrix with variables in columns and $n$ observations $\mathbf x_i$ in rows. If each observation has an associated weight $w_i$, then it is indeed straightforward to incorporate these weights into PCA. First, one needs to compute the weighted mean $\boldsymbol \mu = \frac{1}{\sum w_i}\sum w_i \mathbf x_i$ and subtract it from the data in order to center it. Then we compute the weighted covariance matrix $\frac{1}{\sum w_i}\mathbf X^\top \mathbf W \mathbf X$, where $\mathbf W = \operatorname{diag}(w_i)$ is the diagonal matrix of weights, and apply standard PCA to analyze it. Cell weights The paper by Tamuz et al., 2013, that you found, considers a more complicated case when different weights $w_{ij}$ are applied to each element of the data matrix. Then indeed there is no analytical solution and one has to use an iterative method. Note that, as acknowledged by the authors, they reinvented the wheel, as such general weights have certainly been considered before, e.g. in Gabriel and Zamir, 1979, Lower Rank Approximation of Matrices by Least Squares With Any Choice of Weights. This was also discussed here. As an additional remark: if the weights $w_{ij}$ vary with both variables and observations, but are symmetric, so that $w_{ij}=w_{ji}$, then analytic solution is possible again, see Koren and Carmel, 2004, Robust Linear Dimensionality Reduction.
Weighted principal components analysis It depends on what exactly your weights apply to. Row weights Let $\mathbf{X}$ be the data matrix with variables in columns and $n$ observations $\mathbf x_i$ in rows. If each observation has an assoc
13,003
Weighted principal components analysis
Thank you very much amoeba for the insight regarding row weights. I know that this is not stackoverflow, but I had some difficulties to find an implementation of row-weighted PCA with explanation and, since this is one of the first results when googling for weighted PCA, I thought it would be good to attach my solution, maybe it can help others in the same situation. In this Python2 code snippet, a PCA weighted with an RBF kernel as the one described above is used to calculate the tangents of a 2D dataset. I will be very happy to hear some feedback! def weighted_pca_regression(x_vec, y_vec, weights): """ Given three real-valued vectors of same length, corresponding to the coordinates and weight of a 2-dimensional dataset, this function outputs the angle in radians of the line that aligns with the (weighted) average and main linear component of the data. For that, first a weighted mean and covariance matrix are computed. Then u,e,v=svd(cov) is performed, and u * f(x)=0 is solved. """ input_mat = np.stack([x_vec, y_vec]) weights_sum = weights.sum() # Subtract (weighted) mean and compute (weighted) covariance matrix: mean_x, mean_y = weights.dot(x_vec)/weights_sum, weights.dot(y_vec)/weights_sum centered_x, centered_y = x_vec-mean_x, y_vec-mean_y matrix_centered = np.stack([centered_x, centered_y]) weighted_cov = matrix_centered.dot(np.diag(weights).dot(matrix_centered.T)) / weights_sum # We know that v rotates the data's main component onto the y=0 axis, and # that u rotates it back. Solving u.dot([x,0])=[x*u[0,0], x*u[1,0]] gives # f(x)=(u[1,0]/u[0,0])x as the reconstructed function. u,e,v = np.linalg.svd(weighted_cov) return np.arctan2(u[1,0], u[0,0]) # arctan more stable than dividing # USAGE EXAMPLE: # Define the kernel and make an ellipse to perform regression on: rbf = lambda vec, stddev: np.exp(-0.5*np.power(vec/stddev, 2)) x_span = np.linspace(0, 2*np.pi, 31)+0.1 data_x = np.cos(x_span)[:-1]*20-1000 data_y = np.sin(x_span)[:-1]*10+5000 data_xy = np.stack([data_x, data_y]) stddev = 1 # a stddev of 1 in this context is highly local for center in data_xy.T: # weight the points based on their euclidean distance to the current center euclidean_distances = np.linalg.norm(data_xy.T-center, axis=1) weights = rbf(euclidean_distances, stddev) # get the angle for the regression in radians p_grad = weighted_pca_regression(data_x, data_y, weights) # plot for illustration purposes line_x = np.linspace(-5,5,10) line_y = np.tan(p_grad)*line_x plt.plot(line_x+center[0], line_y+center[1], c="r") plt.scatter(*data_xy) plt.show() And a sample output (it does the same for every dot): Cheers, Andres
Weighted principal components analysis
Thank you very much amoeba for the insight regarding row weights. I know that this is not stackoverflow, but I had some difficulties to find an implementation of row-weighted PCA with explanation and,
Weighted principal components analysis Thank you very much amoeba for the insight regarding row weights. I know that this is not stackoverflow, but I had some difficulties to find an implementation of row-weighted PCA with explanation and, since this is one of the first results when googling for weighted PCA, I thought it would be good to attach my solution, maybe it can help others in the same situation. In this Python2 code snippet, a PCA weighted with an RBF kernel as the one described above is used to calculate the tangents of a 2D dataset. I will be very happy to hear some feedback! def weighted_pca_regression(x_vec, y_vec, weights): """ Given three real-valued vectors of same length, corresponding to the coordinates and weight of a 2-dimensional dataset, this function outputs the angle in radians of the line that aligns with the (weighted) average and main linear component of the data. For that, first a weighted mean and covariance matrix are computed. Then u,e,v=svd(cov) is performed, and u * f(x)=0 is solved. """ input_mat = np.stack([x_vec, y_vec]) weights_sum = weights.sum() # Subtract (weighted) mean and compute (weighted) covariance matrix: mean_x, mean_y = weights.dot(x_vec)/weights_sum, weights.dot(y_vec)/weights_sum centered_x, centered_y = x_vec-mean_x, y_vec-mean_y matrix_centered = np.stack([centered_x, centered_y]) weighted_cov = matrix_centered.dot(np.diag(weights).dot(matrix_centered.T)) / weights_sum # We know that v rotates the data's main component onto the y=0 axis, and # that u rotates it back. Solving u.dot([x,0])=[x*u[0,0], x*u[1,0]] gives # f(x)=(u[1,0]/u[0,0])x as the reconstructed function. u,e,v = np.linalg.svd(weighted_cov) return np.arctan2(u[1,0], u[0,0]) # arctan more stable than dividing # USAGE EXAMPLE: # Define the kernel and make an ellipse to perform regression on: rbf = lambda vec, stddev: np.exp(-0.5*np.power(vec/stddev, 2)) x_span = np.linspace(0, 2*np.pi, 31)+0.1 data_x = np.cos(x_span)[:-1]*20-1000 data_y = np.sin(x_span)[:-1]*10+5000 data_xy = np.stack([data_x, data_y]) stddev = 1 # a stddev of 1 in this context is highly local for center in data_xy.T: # weight the points based on their euclidean distance to the current center euclidean_distances = np.linalg.norm(data_xy.T-center, axis=1) weights = rbf(euclidean_distances, stddev) # get the angle for the regression in radians p_grad = weighted_pca_regression(data_x, data_y, weights) # plot for illustration purposes line_x = np.linspace(-5,5,10) line_y = np.tan(p_grad)*line_x plt.plot(line_x+center[0], line_y+center[1], c="r") plt.scatter(*data_xy) plt.show() And a sample output (it does the same for every dot): Cheers, Andres
Weighted principal components analysis Thank you very much amoeba for the insight regarding row weights. I know that this is not stackoverflow, but I had some difficulties to find an implementation of row-weighted PCA with explanation and,
13,004
Auto.arima with daily data: how to capture seasonality/periodicity?
If there is weekly seasonality, set the seasonal period to 7. salests <- ts(data,start=2010,frequency=7) modArima <- auto.arima(salests) Note that the selection of seasonal differencing was not very good in auto.arima() until very recently. If you are using v2.xx of the forecast package, set D=1 in the call to auto.arima() to force seasonal differencing. If you are using v3.xx of the forecast package, the automatic selection of D works much better (using an OCSB test instead of a CH test). Don't try to compare the AIC for models with different levels of differencing. They are not directly comparable. You can only reliably compare the AIC with models having the same orders of differencing. You don't need to re-fit the model after calling auto.arima(). It will return an Arima object, just as if you had called arima() with the selected model order.
Auto.arima with daily data: how to capture seasonality/periodicity?
If there is weekly seasonality, set the seasonal period to 7. salests <- ts(data,start=2010,frequency=7) modArima <- auto.arima(salests) Note that the selection of seasonal differencing was not very
Auto.arima with daily data: how to capture seasonality/periodicity? If there is weekly seasonality, set the seasonal period to 7. salests <- ts(data,start=2010,frequency=7) modArima <- auto.arima(salests) Note that the selection of seasonal differencing was not very good in auto.arima() until very recently. If you are using v2.xx of the forecast package, set D=1 in the call to auto.arima() to force seasonal differencing. If you are using v3.xx of the forecast package, the automatic selection of D works much better (using an OCSB test instead of a CH test). Don't try to compare the AIC for models with different levels of differencing. They are not directly comparable. You can only reliably compare the AIC with models having the same orders of differencing. You don't need to re-fit the model after calling auto.arima(). It will return an Arima object, just as if you had called arima() with the selected model order.
Auto.arima with daily data: how to capture seasonality/periodicity? If there is weekly seasonality, set the seasonal period to 7. salests <- ts(data,start=2010,frequency=7) modArima <- auto.arima(salests) Note that the selection of seasonal differencing was not very
13,005
Auto.arima with daily data: how to capture seasonality/periodicity?
The problem with fitting seasonal ARIMA to daily data is that the "seasonal component" may only operate on the weekends or maybe just the weekdays thus overall there is a non-significnat "seasonal component". Now what you have to do is to augment your data set with 6 dummies representing the days of the week and perhaps monthly indicators to represent annual effects. Now consider incorporating events such as holidays and include any lead, contemoraneous or lag effect around these known variables. No there may be unusual values (pulses) or level shifts or local time trends in the data. Furthermore the day-of-the-week effects may have changed over time e.g. there was no Saturday effect for the first 20 weeks but a Saturday effect for the last 50 weeks.If you wish to post tour daily data I will give it a try and maybe other readers of the list might also contribute their analysis to help guide you through this.
Auto.arima with daily data: how to capture seasonality/periodicity?
The problem with fitting seasonal ARIMA to daily data is that the "seasonal component" may only operate on the weekends or maybe just the weekdays thus overall there is a non-significnat "seasonal com
Auto.arima with daily data: how to capture seasonality/periodicity? The problem with fitting seasonal ARIMA to daily data is that the "seasonal component" may only operate on the weekends or maybe just the weekdays thus overall there is a non-significnat "seasonal component". Now what you have to do is to augment your data set with 6 dummies representing the days of the week and perhaps monthly indicators to represent annual effects. Now consider incorporating events such as holidays and include any lead, contemoraneous or lag effect around these known variables. No there may be unusual values (pulses) or level shifts or local time trends in the data. Furthermore the day-of-the-week effects may have changed over time e.g. there was no Saturday effect for the first 20 weeks but a Saturday effect for the last 50 weeks.If you wish to post tour daily data I will give it a try and maybe other readers of the list might also contribute their analysis to help guide you through this.
Auto.arima with daily data: how to capture seasonality/periodicity? The problem with fitting seasonal ARIMA to daily data is that the "seasonal component" may only operate on the weekends or maybe just the weekdays thus overall there is a non-significnat "seasonal com
13,006
Can a posterior probability be >1?
The assumed conditions do not hold- it can never be true that $P(a)/P(x) < P(a|x)$ by the definition of conditional probability: $P(a|x) = P(a\cap x) / P(x) \leq P(a) / P(x)$
Can a posterior probability be >1?
The assumed conditions do not hold- it can never be true that $P(a)/P(x) < P(a|x)$ by the definition of conditional probability: $P(a|x) = P(a\cap x) / P(x) \leq P(a) / P(x)$
Can a posterior probability be >1? The assumed conditions do not hold- it can never be true that $P(a)/P(x) < P(a|x)$ by the definition of conditional probability: $P(a|x) = P(a\cap x) / P(x) \leq P(a) / P(x)$
Can a posterior probability be >1? The assumed conditions do not hold- it can never be true that $P(a)/P(x) < P(a|x)$ by the definition of conditional probability: $P(a|x) = P(a\cap x) / P(x) \leq P(a) / P(x)$
13,007
Can a posterior probability be >1?
No, it is not possible for the posterior probability to exceed one. That would be a breach of the norming axiom of probability theory. In your question you specify that $\mathbb{P}(a)/\mathbb{P}(x) < \mathbb{P}(a | x)$ as part of your example. However, using the rules of conditional probability, you must have: $$\mathbb{P}(a | x) = \frac{\mathbb{P}(a,x)}{\mathbb{P}(x)} \leqslant \frac{\mathbb{P}(a)}{\mathbb{P}(x)}.$$ This means that you cannot have the inequality conditions you have specified. (Incidentally, this is a good question: it is good that you are probing the probability laws looking for problems. It shows that you are exploring these matters with a greater degree of rigour than most students.) An additional point: It is worth making one additional point about this situation, which is about the logical priority of different characteristics of probability. Remember that probability theory starts with a set of axioms that characterise what a probability measure actually is. From these axioms we can derive "rules of probability" which are theorems derived from the axioms. These rules of probability must be consistent with the axioms to be valid. If you ever found that a rule of probability leads to a contradiction with one of the axioms (e.g., the probability of the sample space is greater than one), this would not falsify the axiom - it would falsify the probability rule. Hence, even if it were the case the Bayes' rule could lead to a posterior probability greater than one (it doesn't), this wouldn't mean that you can have a posterior probability greater than one; it would simply mean that Bayes' rule is not a valid rule of probability.
Can a posterior probability be >1?
No, it is not possible for the posterior probability to exceed one. That would be a breach of the norming axiom of probability theory. In your question you specify that $\mathbb{P}(a)/\mathbb{P}(x)
Can a posterior probability be >1? No, it is not possible for the posterior probability to exceed one. That would be a breach of the norming axiom of probability theory. In your question you specify that $\mathbb{P}(a)/\mathbb{P}(x) < \mathbb{P}(a | x)$ as part of your example. However, using the rules of conditional probability, you must have: $$\mathbb{P}(a | x) = \frac{\mathbb{P}(a,x)}{\mathbb{P}(x)} \leqslant \frac{\mathbb{P}(a)}{\mathbb{P}(x)}.$$ This means that you cannot have the inequality conditions you have specified. (Incidentally, this is a good question: it is good that you are probing the probability laws looking for problems. It shows that you are exploring these matters with a greater degree of rigour than most students.) An additional point: It is worth making one additional point about this situation, which is about the logical priority of different characteristics of probability. Remember that probability theory starts with a set of axioms that characterise what a probability measure actually is. From these axioms we can derive "rules of probability" which are theorems derived from the axioms. These rules of probability must be consistent with the axioms to be valid. If you ever found that a rule of probability leads to a contradiction with one of the axioms (e.g., the probability of the sample space is greater than one), this would not falsify the axiom - it would falsify the probability rule. Hence, even if it were the case the Bayes' rule could lead to a posterior probability greater than one (it doesn't), this wouldn't mean that you can have a posterior probability greater than one; it would simply mean that Bayes' rule is not a valid rule of probability.
Can a posterior probability be >1? No, it is not possible for the posterior probability to exceed one. That would be a breach of the norming axiom of probability theory. In your question you specify that $\mathbb{P}(a)/\mathbb{P}(x)
13,008
Can a posterior probability be >1?
The Bayes formula $\displaystyle P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)}$ cannot give values for $P(B\mid A)$ exceeding $1$. An intuitive way to see this is to express $P(A)$ via the law of total probability as $$P(A) = P(A\mid B)P(B) + P(A\mid B^c)P(B^c)$$ giving that $$P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)} = \frac{P(A\mid B)P(B)}{P(A\mid B)P(B) + P(A\mid B^c)P(B^c)}$$ which shows that the numerator is just one of the terms in the sum in the denominator, and so the fraction cannot exceed $1$ in value.
Can a posterior probability be >1?
The Bayes formula $\displaystyle P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)}$ cannot give values for $P(B\mid A)$ exceeding $1$. An intuitive way to see this is to express $P(A)$ via the law of total pr
Can a posterior probability be >1? The Bayes formula $\displaystyle P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)}$ cannot give values for $P(B\mid A)$ exceeding $1$. An intuitive way to see this is to express $P(A)$ via the law of total probability as $$P(A) = P(A\mid B)P(B) + P(A\mid B^c)P(B^c)$$ giving that $$P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)} = \frac{P(A\mid B)P(B)}{P(A\mid B)P(B) + P(A\mid B^c)P(B^c)}$$ which shows that the numerator is just one of the terms in the sum in the denominator, and so the fraction cannot exceed $1$ in value.
Can a posterior probability be >1? The Bayes formula $\displaystyle P(B \mid A) = \frac{P(A\mid B)P(B)}{P(A)}$ cannot give values for $P(B\mid A)$ exceeding $1$. An intuitive way to see this is to express $P(A)$ via the law of total pr
13,009
$P[X=x]=0$ when $X$ is a continuous variable
Probabilities are models for the relative frequencies of observations. If an event $A$ is observed to have occurred $N_A$ times on $N$ trials, then its relative frequency is $$\text{relative frequency of }(A) = \frac{N_A}{N}$$ and it is generally believed that the numerical value of the above ratio is a close approximation to $P(A)$ when $N$ is "large" where what is meant by "large" is best left to the imagination (and credulity) of the reader. Now, it has been observed that if our model of $X$ is that of a continuous random variable, then the samples of $X$ $\{x_1, x_2, \ldots, x_N\}$ are $N$ distinct numbers. Thus, the relative frequency of a specific number $x$ (or, more pedantically, the event $\{X = x\}$) is either $\frac 1N$ if one of the $x_i$ has value $x$, or $\frac 0N$ if all the $x_i$ are different from $x$. If a more skeptical reader collects an additional $N$ samples, the relative frequency of the event $\{X=x\}$ is either $\frac{1}{2N}$ or continues to enjoy the value $\frac 0N$. Thus, one is tempted to guess that $P\{X = x\}$ should be assigned the value $0$ since that is a good approximation to the observed relative frequency. Note: the above explanation is (usually) satisfactory to engineers and others interested in the application of probability and statistics (i.e. those who believe that the axioms of probability were chosen so as to make the theory a good model of reality), but totally unsatisfactory to many others. It is also possible to approach your question from a purely mathematical or statistical perspective and prove that $P\{X = x\}$ must have value $0$ whenever $X$ is a continuous random variable via logical deductions from the axioms of probability, and without any reference to relative frequency or physical observations etc.
$P[X=x]=0$ when $X$ is a continuous variable
Probabilities are models for the relative frequencies of observations. If an event $A$ is observed to have occurred $N_A$ times on $N$ trials, then its relative frequency is $$\text{relative frequenc
$P[X=x]=0$ when $X$ is a continuous variable Probabilities are models for the relative frequencies of observations. If an event $A$ is observed to have occurred $N_A$ times on $N$ trials, then its relative frequency is $$\text{relative frequency of }(A) = \frac{N_A}{N}$$ and it is generally believed that the numerical value of the above ratio is a close approximation to $P(A)$ when $N$ is "large" where what is meant by "large" is best left to the imagination (and credulity) of the reader. Now, it has been observed that if our model of $X$ is that of a continuous random variable, then the samples of $X$ $\{x_1, x_2, \ldots, x_N\}$ are $N$ distinct numbers. Thus, the relative frequency of a specific number $x$ (or, more pedantically, the event $\{X = x\}$) is either $\frac 1N$ if one of the $x_i$ has value $x$, or $\frac 0N$ if all the $x_i$ are different from $x$. If a more skeptical reader collects an additional $N$ samples, the relative frequency of the event $\{X=x\}$ is either $\frac{1}{2N}$ or continues to enjoy the value $\frac 0N$. Thus, one is tempted to guess that $P\{X = x\}$ should be assigned the value $0$ since that is a good approximation to the observed relative frequency. Note: the above explanation is (usually) satisfactory to engineers and others interested in the application of probability and statistics (i.e. those who believe that the axioms of probability were chosen so as to make the theory a good model of reality), but totally unsatisfactory to many others. It is also possible to approach your question from a purely mathematical or statistical perspective and prove that $P\{X = x\}$ must have value $0$ whenever $X$ is a continuous random variable via logical deductions from the axioms of probability, and without any reference to relative frequency or physical observations etc.
$P[X=x]=0$ when $X$ is a continuous variable Probabilities are models for the relative frequencies of observations. If an event $A$ is observed to have occurred $N_A$ times on $N$ trials, then its relative frequency is $$\text{relative frequenc
13,010
$P[X=x]=0$ when $X$ is a continuous variable
Let $(\Omega,\mathscr{F},P)$ be the underlying probability space. We say that a measurable function $X:\Omega\to\mathbb{R}$ is an absolutely continuous random variable if the probability measure $\mu_X$ over $(\mathbb{R},\mathscr{B})$ defined by $\mu_X(B)=P\{X\in B\}$, known as the distribution of $X$, is dominated by Lebesgue measure $\lambda$, in the sense that for every Borel set $B$, if $\lambda(B)=0$, then $\mu_X(B)=0$. In this case, the Radon-Nikodym theorem tells us that there is a measurable $f_X:\mathbb{R}\to\mathbb{R}$, defined up to almost everywhere equivalence, such that $\mu_X(B)=\int_B f(x)\,d\lambda(x)$. Let $B=\{x_1,x_2,\dots\}$ be a countable subset of $\mathbb{R}$. Since $\lambda$ is countably additive, $\lambda(B)=\lambda\left(\cup_{i\geq 1}\{x_i\}\right)=\sum_{i\geq 1}\lambda(\{x_i\})$. But $$ \lambda(\{x_i\}) = \lambda\left(\cap_{k\geq 1}[x_i,x_i+1/k)\right) \leq \lambda\left([x_i,x_i+1/n)\right) = \frac{1}{n} \, ,\qquad (*) $$ for every $n\geq 1$. Due to the Archimedean property of the real numbers, since $\lambda(\{x_i\})\geq 0$, the inequality $(*)$ holds for every $n\geq 1$ if and only if $\lambda(\{x_i\})=0$, entailing that $\lambda(B)=0$. From the assumed absolute continuity of $X$ it follows that $\mu_X(B)=P\{X\in B\}=0$.
$P[X=x]=0$ when $X$ is a continuous variable
Let $(\Omega,\mathscr{F},P)$ be the underlying probability space. We say that a measurable function $X:\Omega\to\mathbb{R}$ is an absolutely continuous random variable if the probability measure $\mu_
$P[X=x]=0$ when $X$ is a continuous variable Let $(\Omega,\mathscr{F},P)$ be the underlying probability space. We say that a measurable function $X:\Omega\to\mathbb{R}$ is an absolutely continuous random variable if the probability measure $\mu_X$ over $(\mathbb{R},\mathscr{B})$ defined by $\mu_X(B)=P\{X\in B\}$, known as the distribution of $X$, is dominated by Lebesgue measure $\lambda$, in the sense that for every Borel set $B$, if $\lambda(B)=0$, then $\mu_X(B)=0$. In this case, the Radon-Nikodym theorem tells us that there is a measurable $f_X:\mathbb{R}\to\mathbb{R}$, defined up to almost everywhere equivalence, such that $\mu_X(B)=\int_B f(x)\,d\lambda(x)$. Let $B=\{x_1,x_2,\dots\}$ be a countable subset of $\mathbb{R}$. Since $\lambda$ is countably additive, $\lambda(B)=\lambda\left(\cup_{i\geq 1}\{x_i\}\right)=\sum_{i\geq 1}\lambda(\{x_i\})$. But $$ \lambda(\{x_i\}) = \lambda\left(\cap_{k\geq 1}[x_i,x_i+1/k)\right) \leq \lambda\left([x_i,x_i+1/n)\right) = \frac{1}{n} \, ,\qquad (*) $$ for every $n\geq 1$. Due to the Archimedean property of the real numbers, since $\lambda(\{x_i\})\geq 0$, the inequality $(*)$ holds for every $n\geq 1$ if and only if $\lambda(\{x_i\})=0$, entailing that $\lambda(B)=0$. From the assumed absolute continuity of $X$ it follows that $\mu_X(B)=P\{X\in B\}=0$.
$P[X=x]=0$ when $X$ is a continuous variable Let $(\Omega,\mathscr{F},P)$ be the underlying probability space. We say that a measurable function $X:\Omega\to\mathbb{R}$ is an absolutely continuous random variable if the probability measure $\mu_
13,011
$P[X=x]=0$ when $X$ is a continuous variable
$X$ is a continuous random variable means its distribution function $F$ is continuous. This is the only condition we have but from which we can derive that $P(X = x) = 0$. In fact, by continuity of $F$, we have $F(x) = F(x-)$ for every $x \in \mathbb{R}^1$, therefore: $$P(X = x) = P(X \leq x) - P(X < x) = F(x) - F(x-) = 0.$$
$P[X=x]=0$ when $X$ is a continuous variable
$X$ is a continuous random variable means its distribution function $F$ is continuous. This is the only condition we have but from which we can derive that $P(X = x) = 0$. In fact, by continuity of $
$P[X=x]=0$ when $X$ is a continuous variable $X$ is a continuous random variable means its distribution function $F$ is continuous. This is the only condition we have but from which we can derive that $P(X = x) = 0$. In fact, by continuity of $F$, we have $F(x) = F(x-)$ for every $x \in \mathbb{R}^1$, therefore: $$P(X = x) = P(X \leq x) - P(X < x) = F(x) - F(x-) = 0.$$
$P[X=x]=0$ when $X$ is a continuous variable $X$ is a continuous random variable means its distribution function $F$ is continuous. This is the only condition we have but from which we can derive that $P(X = x) = 0$. In fact, by continuity of $
13,012
$P[X=x]=0$ when $X$ is a continuous variable
This is really a question about probabilities. It could be rephrased something like Suppose there are an infinite number of disjoint events. Why must their probabilities eventually become arbitrarily small? Well, if they didn't become small, there would be a positive number $\epsilon$ smaller than all those probabilities. One axiom of probability implies the probability of a union of a finite number of distinct events is the sum of their probabilities. Since "infinite" means there exist finite subsets of any size $n,$ we at least know that for any whole number $n$ there is a set of $n$ distinct events of probability $\epsilon$ or greater. Taking $n \gt 1/\epsilon$ (guaranteed by the Archimedean property of real numbers) we would deduce the existence of a collection of disjoint events whose probability exceeds $n\epsilon\gt 1,$ an obvious impossibility. This completes the proof: we are obliged to conclude the original assumption is false: namely, the probabilities do become arbitrarily small. BTW, it should be no mystery why an infinite number of disjoint events can all have zero probability. Take the simplest kind of random variable: the constant $X=0.$ For any nonzero $x,$ obviously $\Pr(X=x) = 0.$ There are a lot of such $x$! The problem really is, how can it be possible that $\Pr(X=x)=0$ for all possible values $x$ without forcing all probabilities to be zero? The formal mathematical answer is buried in the probability axioms: they do not state, nor even imply, that the probability of an event must be the sum of the probabilities of all its elements. This is the subtlety in the restriction to countable unions and countable sums. The real numbers are not countable. But then how do you visualize such a thing? The cumulative distribution function $F_X$ of any random variable $X$ is a useful tool. By definition, for any number $x,$ $F_X(x)$ is the chance that $X \le x,$ written $\Pr(X\le x).$ We can (and usually do) draw a graph of $F_X.$ The probability axioms imply its heights must lie between $0$ and $1$ (they are all probabilities, after all) and that the graph never decreases as you increase $x.$ (This latter is proven by noting that for $y\gt x,$ $F(y)-F(x) = \Pr(y \lt X \le x) \ge 0.$) Using the CDF, then, we find that the probability of $X=x$ is the amount by which the graph of $F$ rises at $x$ as you move left to right. In any continuous such graph, all such rises are zero (that's essentially the definition of "continuous"). Nevertheless, despite rising by an amount $0$ at every point $x,$ somehow the graph manages to increase its elevation from $0$ to $1$ throughout its domain. See Wikipedia (at "CDF") for some examples. Pondering this visually evident fact might help you appreciate these issues better. For a more insight, study Zeno's Paradoxes.
$P[X=x]=0$ when $X$ is a continuous variable
This is really a question about probabilities. It could be rephrased something like Suppose there are an infinite number of disjoint events. Why must their probabilities eventually become arbitrarily
$P[X=x]=0$ when $X$ is a continuous variable This is really a question about probabilities. It could be rephrased something like Suppose there are an infinite number of disjoint events. Why must their probabilities eventually become arbitrarily small? Well, if they didn't become small, there would be a positive number $\epsilon$ smaller than all those probabilities. One axiom of probability implies the probability of a union of a finite number of distinct events is the sum of their probabilities. Since "infinite" means there exist finite subsets of any size $n,$ we at least know that for any whole number $n$ there is a set of $n$ distinct events of probability $\epsilon$ or greater. Taking $n \gt 1/\epsilon$ (guaranteed by the Archimedean property of real numbers) we would deduce the existence of a collection of disjoint events whose probability exceeds $n\epsilon\gt 1,$ an obvious impossibility. This completes the proof: we are obliged to conclude the original assumption is false: namely, the probabilities do become arbitrarily small. BTW, it should be no mystery why an infinite number of disjoint events can all have zero probability. Take the simplest kind of random variable: the constant $X=0.$ For any nonzero $x,$ obviously $\Pr(X=x) = 0.$ There are a lot of such $x$! The problem really is, how can it be possible that $\Pr(X=x)=0$ for all possible values $x$ without forcing all probabilities to be zero? The formal mathematical answer is buried in the probability axioms: they do not state, nor even imply, that the probability of an event must be the sum of the probabilities of all its elements. This is the subtlety in the restriction to countable unions and countable sums. The real numbers are not countable. But then how do you visualize such a thing? The cumulative distribution function $F_X$ of any random variable $X$ is a useful tool. By definition, for any number $x,$ $F_X(x)$ is the chance that $X \le x,$ written $\Pr(X\le x).$ We can (and usually do) draw a graph of $F_X.$ The probability axioms imply its heights must lie between $0$ and $1$ (they are all probabilities, after all) and that the graph never decreases as you increase $x.$ (This latter is proven by noting that for $y\gt x,$ $F(y)-F(x) = \Pr(y \lt X \le x) \ge 0.$) Using the CDF, then, we find that the probability of $X=x$ is the amount by which the graph of $F$ rises at $x$ as you move left to right. In any continuous such graph, all such rises are zero (that's essentially the definition of "continuous"). Nevertheless, despite rising by an amount $0$ at every point $x,$ somehow the graph manages to increase its elevation from $0$ to $1$ throughout its domain. See Wikipedia (at "CDF") for some examples. Pondering this visually evident fact might help you appreciate these issues better. For a more insight, study Zeno's Paradoxes.
$P[X=x]=0$ when $X$ is a continuous variable This is really a question about probabilities. It could be rephrased something like Suppose there are an infinite number of disjoint events. Why must their probabilities eventually become arbitrarily
13,013
$P[X=x]=0$ when $X$ is a continuous variable
There are many answers here which address the technical reasons for why infinitesimally small slices of a continuous probability distribution, $Pr(X=x)$, are 0. The key idea here is that this probability is uncountable. Instead of adding to the mathematically driven answers here, I would like to connect this phenomenon to a real-world example (with a frequentist approach): Imagine you are analyzing the (gaussian) distribution of temperatures for a particular time at a particular place. Let's say noon, Jan 1st, in Cambridge. Population: $\mu = 0$ and $\sigma = 10$ You can comfortably say that 95% of sample temperatures means will fall between ~ $-20$ and $20$. Shrink down that range and recompute your conf. interval. Rinse and repeat. Eventually, you are left with the interval of $-0.000001$ and $0.000001$. What percentage of sample means would fall into that interval? A very small percentage in a technical sense, but in reality, most people would assign it $0$% upon some thought. How would you even measure such a precise temperature? As you continue to shrink the interval until both the positive and negative limits approach $0$, you'd need to find more and more precise measurement tools. Eventually, you'll run out of precision. In truth, it's almost never going to be exactly 0 degrees at noon, and even if it were, you wouldn't have any way to measure it. Thus, we assign zero probability to infinitesimally specific events in a continuous distribution.
$P[X=x]=0$ when $X$ is a continuous variable
There are many answers here which address the technical reasons for why infinitesimally small slices of a continuous probability distribution, $Pr(X=x)$, are 0. The key idea here is that this probabil
$P[X=x]=0$ when $X$ is a continuous variable There are many answers here which address the technical reasons for why infinitesimally small slices of a continuous probability distribution, $Pr(X=x)$, are 0. The key idea here is that this probability is uncountable. Instead of adding to the mathematically driven answers here, I would like to connect this phenomenon to a real-world example (with a frequentist approach): Imagine you are analyzing the (gaussian) distribution of temperatures for a particular time at a particular place. Let's say noon, Jan 1st, in Cambridge. Population: $\mu = 0$ and $\sigma = 10$ You can comfortably say that 95% of sample temperatures means will fall between ~ $-20$ and $20$. Shrink down that range and recompute your conf. interval. Rinse and repeat. Eventually, you are left with the interval of $-0.000001$ and $0.000001$. What percentage of sample means would fall into that interval? A very small percentage in a technical sense, but in reality, most people would assign it $0$% upon some thought. How would you even measure such a precise temperature? As you continue to shrink the interval until both the positive and negative limits approach $0$, you'd need to find more and more precise measurement tools. Eventually, you'll run out of precision. In truth, it's almost never going to be exactly 0 degrees at noon, and even if it were, you wouldn't have any way to measure it. Thus, we assign zero probability to infinitesimally specific events in a continuous distribution.
$P[X=x]=0$ when $X$ is a continuous variable There are many answers here which address the technical reasons for why infinitesimally small slices of a continuous probability distribution, $Pr(X=x)$, are 0. The key idea here is that this probabil
13,014
$P[X=x]=0$ when $X$ is a continuous variable
This question is very simple. PDF is the density, then to get the probability you need to multiply it by the width of the region. So, when you get a smaller region around the point of interest $x$ the height of the density doesn't change, hence the probability is smaller and smaller while you squeeze the area around your point until it becomes exactly zero. The difficult question is the reverse one, like this: https://stats.stackexchange.com/a/273407/36041
$P[X=x]=0$ when $X$ is a continuous variable
This question is very simple. PDF is the density, then to get the probability you need to multiply it by the width of the region. So, when you get a smaller region around the point of interest $x$ the
$P[X=x]=0$ when $X$ is a continuous variable This question is very simple. PDF is the density, then to get the probability you need to multiply it by the width of the region. So, when you get a smaller region around the point of interest $x$ the height of the density doesn't change, hence the probability is smaller and smaller while you squeeze the area around your point until it becomes exactly zero. The difficult question is the reverse one, like this: https://stats.stackexchange.com/a/273407/36041
$P[X=x]=0$ when $X$ is a continuous variable This question is very simple. PDF is the density, then to get the probability you need to multiply it by the width of the region. So, when you get a smaller region around the point of interest $x$ the
13,015
Fitting t-distribution in R: scaling parameter
fitdistr uses maximum-likelihood and optimization techniques to find parameters of a given distribution. Sometimes, especially for t-distribution, as @user12719 noticed, the optimization in the form: fitdistr(x, "t") fails with an error. In this case you should give optimizer a hand by providing starting point and lower bound to start searching for optimal parameters: fitdistr(x, "t", start = list(m=mean(x),s=sd(x), df=3), lower=c(-1, 0.001,1)) Note, df=3 is your best guess at what an "optimal" df could be. After providing this additional info your error will be gone. Couple of excerpts to help you better understand the inner mechanics of fitdistr: For the Normal, log-Normal, geometric, exponential and Poisson distributions the closed-form MLEs (and exact standard errors) are used, and start should not be supplied. ... For the following named distributions, reasonable starting values will be computed if start is omitted or only partially specified: "cauchy", "gamma", "logistic", "negative binomial" (parametrized by mu and size), "t" and "weibull". Note that these starting values may not be good enough if the fit is poor: in particular they are not resistant to outliers unless the fitted distribution is long-tailed.
Fitting t-distribution in R: scaling parameter
fitdistr uses maximum-likelihood and optimization techniques to find parameters of a given distribution. Sometimes, especially for t-distribution, as @user12719 noticed, the optimization in the form:
Fitting t-distribution in R: scaling parameter fitdistr uses maximum-likelihood and optimization techniques to find parameters of a given distribution. Sometimes, especially for t-distribution, as @user12719 noticed, the optimization in the form: fitdistr(x, "t") fails with an error. In this case you should give optimizer a hand by providing starting point and lower bound to start searching for optimal parameters: fitdistr(x, "t", start = list(m=mean(x),s=sd(x), df=3), lower=c(-1, 0.001,1)) Note, df=3 is your best guess at what an "optimal" df could be. After providing this additional info your error will be gone. Couple of excerpts to help you better understand the inner mechanics of fitdistr: For the Normal, log-Normal, geometric, exponential and Poisson distributions the closed-form MLEs (and exact standard errors) are used, and start should not be supplied. ... For the following named distributions, reasonable starting values will be computed if start is omitted or only partially specified: "cauchy", "gamma", "logistic", "negative binomial" (parametrized by mu and size), "t" and "weibull". Note that these starting values may not be good enough if the fit is poor: in particular they are not resistant to outliers unless the fitted distribution is long-tailed.
Fitting t-distribution in R: scaling parameter fitdistr uses maximum-likelihood and optimization techniques to find parameters of a given distribution. Sometimes, especially for t-distribution, as @user12719 noticed, the optimization in the form:
13,016
Fitting t-distribution in R: scaling parameter
MASS, the book (4th edition, page 110) advises against trying to estimate $\nu$, the degrees of freedom parameter in the $t$-distribution with maximum likelihood (with some literature references: Lange et al. (1989), "Robust statistical modeling Using the t distribution", JASA, 84, 408, and Fernandez & Steel (1999), "Multivariate Student-t regression models: Pitfalls and inference", Biometrika, 86, 1). The reason is that the likelihood function for $\nu$ based on the t density function, may be unbounded and will in those cases not give a well defined maximum. Let us look at an artificial example where location and scale is known (as the standard $t$-distribution) and only the degrees of freedom is unknown. Below is some R code, simulating some data, defining the log-likelihood function and plotting it: set.seed(1234) n <- 10 x <- rt(n, df=2.5) make_loglik <- function(x) Vectorize( function(nu) sum(dt(x, df=nu, log=TRUE)) ) loglik <- make_loglik(x) plot(loglik, from=1, to=100, main="loglikelihood function for df parameter", xlab="degrees of freedom") abline(v=2.5, col="red2") If you play around with this code, you can find some cases where there is a well-defined maximum, especially when the sample size $n$ is large. But is the maximum likelihood estimator then any good? Let us try some simulations: t_nu_mle <- function(x) { loglik <- make_loglik(x) res <- optimize(loglik, interval=c(0.01, 200), maximum=TRUE)$maximum res } nus <- replicate(1000, {x <- rt(10, df=2.5) t_nu_mle(x) }, simplify=TRUE) > mean(nus) [1] 45.20767 > sd(nus) [1] 78.77813 Showing the estimation is very unstable (looking at the histogram, a sizable portion of the estimated values is at the upper limit given to optimize of 200). Repeating with a larger sample size: nus <- replicate(1000, {x <- rt(50, df=2.5) t_nu_mle(x) }, simplify=TRUE) > mean(nus) [1] 4.342724 > sd(nus) [1] 14.40137 which is much better, but the mean is still way above the true value of 2.5. Then remember that this is a simplified version of the real problem where location and scale parameters also have to be estimated. If the reason of using the $t$-distribution is to "robustify", then estimating $\nu$ from the data may well destroy the robustness.
Fitting t-distribution in R: scaling parameter
MASS, the book (4th edition, page 110) advises against trying to estimate $\nu$, the degrees of freedom parameter in the $t$-distribution with maximum likelihood (with some literature references: Lang
Fitting t-distribution in R: scaling parameter MASS, the book (4th edition, page 110) advises against trying to estimate $\nu$, the degrees of freedom parameter in the $t$-distribution with maximum likelihood (with some literature references: Lange et al. (1989), "Robust statistical modeling Using the t distribution", JASA, 84, 408, and Fernandez & Steel (1999), "Multivariate Student-t regression models: Pitfalls and inference", Biometrika, 86, 1). The reason is that the likelihood function for $\nu$ based on the t density function, may be unbounded and will in those cases not give a well defined maximum. Let us look at an artificial example where location and scale is known (as the standard $t$-distribution) and only the degrees of freedom is unknown. Below is some R code, simulating some data, defining the log-likelihood function and plotting it: set.seed(1234) n <- 10 x <- rt(n, df=2.5) make_loglik <- function(x) Vectorize( function(nu) sum(dt(x, df=nu, log=TRUE)) ) loglik <- make_loglik(x) plot(loglik, from=1, to=100, main="loglikelihood function for df parameter", xlab="degrees of freedom") abline(v=2.5, col="red2") If you play around with this code, you can find some cases where there is a well-defined maximum, especially when the sample size $n$ is large. But is the maximum likelihood estimator then any good? Let us try some simulations: t_nu_mle <- function(x) { loglik <- make_loglik(x) res <- optimize(loglik, interval=c(0.01, 200), maximum=TRUE)$maximum res } nus <- replicate(1000, {x <- rt(10, df=2.5) t_nu_mle(x) }, simplify=TRUE) > mean(nus) [1] 45.20767 > sd(nus) [1] 78.77813 Showing the estimation is very unstable (looking at the histogram, a sizable portion of the estimated values is at the upper limit given to optimize of 200). Repeating with a larger sample size: nus <- replicate(1000, {x <- rt(50, df=2.5) t_nu_mle(x) }, simplify=TRUE) > mean(nus) [1] 4.342724 > sd(nus) [1] 14.40137 which is much better, but the mean is still way above the true value of 2.5. Then remember that this is a simplified version of the real problem where location and scale parameters also have to be estimated. If the reason of using the $t$-distribution is to "robustify", then estimating $\nu$ from the data may well destroy the robustness.
Fitting t-distribution in R: scaling parameter MASS, the book (4th edition, page 110) advises against trying to estimate $\nu$, the degrees of freedom parameter in the $t$-distribution with maximum likelihood (with some literature references: Lang
13,017
Fitting t-distribution in R: scaling parameter
In the help for fitdistr is this example: fitdistr(x2, "t", df = 9) indicating that you just need a value for df. But that assumes standardization. For more control, they also show mydt <- function(x, m, s, df) dt((x-m)/s, df)/s fitdistr(x2, mydt, list(m = 0, s = 1), df = 9, lower = c(-Inf, 0)) where the parameters would be m = mean, s = standard deviation, df = degrees of freedom
Fitting t-distribution in R: scaling parameter
In the help for fitdistr is this example: fitdistr(x2, "t", df = 9) indicating that you just need a value for df. But that assumes standardization. For more control, they also show mydt <- function(x
Fitting t-distribution in R: scaling parameter In the help for fitdistr is this example: fitdistr(x2, "t", df = 9) indicating that you just need a value for df. But that assumes standardization. For more control, they also show mydt <- function(x, m, s, df) dt((x-m)/s, df)/s fitdistr(x2, mydt, list(m = 0, s = 1), df = 9, lower = c(-Inf, 0)) where the parameters would be m = mean, s = standard deviation, df = degrees of freedom
Fitting t-distribution in R: scaling parameter In the help for fitdistr is this example: fitdistr(x2, "t", df = 9) indicating that you just need a value for df. But that assumes standardization. For more control, they also show mydt <- function(x
13,018
Fitting t-distribution in R: scaling parameter
You can use fitdistrplus library after extending the location and scaling parameters for the student t in base R according to this article on wikipedia. Below is sample code library(fitdistrplus) x<-rt(100,23) dt_ls <- function(x, df=1, mu=0, sigma=1) 1/sigma * dt((x - mu)/sigma, df) pt_ls <- function(q, df=1, mu=0, sigma=1) pt((q - mu)/sigma, df) qt_ls <- function(p, df=1, mu=0, sigma=1) qt(p, df)*sigma + mu rt_ls <- function(n, df=1, mu=0, sigma=1) rt(n,df)*sigma + mu fit.t<-fitdist(x, 't_ls', start =list(df=1,mu=mean(x),sigma=sd(x))) summary(fit.t)
Fitting t-distribution in R: scaling parameter
You can use fitdistrplus library after extending the location and scaling parameters for the student t in base R according to this article on wikipedia. Below is sample code library(fitdistrplus) x<-r
Fitting t-distribution in R: scaling parameter You can use fitdistrplus library after extending the location and scaling parameters for the student t in base R according to this article on wikipedia. Below is sample code library(fitdistrplus) x<-rt(100,23) dt_ls <- function(x, df=1, mu=0, sigma=1) 1/sigma * dt((x - mu)/sigma, df) pt_ls <- function(q, df=1, mu=0, sigma=1) pt((q - mu)/sigma, df) qt_ls <- function(p, df=1, mu=0, sigma=1) qt(p, df)*sigma + mu rt_ls <- function(n, df=1, mu=0, sigma=1) rt(n,df)*sigma + mu fit.t<-fitdist(x, 't_ls', start =list(df=1,mu=mean(x),sigma=sd(x))) summary(fit.t)
Fitting t-distribution in R: scaling parameter You can use fitdistrplus library after extending the location and scaling parameters for the student t in base R according to this article on wikipedia. Below is sample code library(fitdistrplus) x<-r
13,019
Fitting t-distribution in R: scaling parameter
The parameters of the t-distribution are referred to as the location, scale, and degrees of freedom $\nu$. The location can be estimated by the mean of the samples if $\nu > 1$; otherwise the mean is not defined. By not defined, this means that increasing the sample size will not converge to a particular value. The scale is a generalization of the standard-deviation. The scale $\sigma$ can be estimated from the standard-deviation of the samples if $\nu > 2$. $\sigma_{est} = E[(X-\mu)^2]^{1/2} sqrt[(\nu - 2)/\nu]$. In addition to the established methods, new closed-formed estimates that achieve the maximum likelihood have been defined in two papers. In my paper "Use of the geometric mean as a statistic for the scale of the coupled Gaussian distribution" The Coupled Gaussian is equivalent to the Student's t but is expressed in terms of the shape or coupling, which is inverse to $\nu$. I showed a functional relationship between the scale, DoF and the geometric mean. Thus the function can be used to estimate either scale or DoF if the other is known. In my paper "Independent Approximates enable closed-form estimation of heavy-tailed distributions" I showed that linear closed-form functions exist for estimating the location and scale parameters of the Student's t distribution. These functions are formed by selecting subsamples referred to as Independent Approximates (IAs). The IAs are formed by pairs, triplets, or n-tuples that are approximately equal. The IA-pairs are guaranteed to have a mean and can be used to estimate the location. The IA-triplets are guaranteed to have a finite second-moment and can be used to estimate the scale. There is Mathematica code referenced in the IA paper. Perhaps someone would be interested in implementing the method in R.
Fitting t-distribution in R: scaling parameter
The parameters of the t-distribution are referred to as the location, scale, and degrees of freedom $\nu$. The location can be estimated by the mean of the samples if $\nu > 1$; otherwise the mean is
Fitting t-distribution in R: scaling parameter The parameters of the t-distribution are referred to as the location, scale, and degrees of freedom $\nu$. The location can be estimated by the mean of the samples if $\nu > 1$; otherwise the mean is not defined. By not defined, this means that increasing the sample size will not converge to a particular value. The scale is a generalization of the standard-deviation. The scale $\sigma$ can be estimated from the standard-deviation of the samples if $\nu > 2$. $\sigma_{est} = E[(X-\mu)^2]^{1/2} sqrt[(\nu - 2)/\nu]$. In addition to the established methods, new closed-formed estimates that achieve the maximum likelihood have been defined in two papers. In my paper "Use of the geometric mean as a statistic for the scale of the coupled Gaussian distribution" The Coupled Gaussian is equivalent to the Student's t but is expressed in terms of the shape or coupling, which is inverse to $\nu$. I showed a functional relationship between the scale, DoF and the geometric mean. Thus the function can be used to estimate either scale or DoF if the other is known. In my paper "Independent Approximates enable closed-form estimation of heavy-tailed distributions" I showed that linear closed-form functions exist for estimating the location and scale parameters of the Student's t distribution. These functions are formed by selecting subsamples referred to as Independent Approximates (IAs). The IAs are formed by pairs, triplets, or n-tuples that are approximately equal. The IA-pairs are guaranteed to have a mean and can be used to estimate the location. The IA-triplets are guaranteed to have a finite second-moment and can be used to estimate the scale. There is Mathematica code referenced in the IA paper. Perhaps someone would be interested in implementing the method in R.
Fitting t-distribution in R: scaling parameter The parameters of the t-distribution are referred to as the location, scale, and degrees of freedom $\nu$. The location can be estimated by the mean of the samples if $\nu > 1$; otherwise the mean is
13,020
Fitting t-distribution in R: scaling parameter
@SergeyBushmanov points out that sometimes you need to give maximum likelihood estimation a hand by providing appropriate starting point and lower/upper bounds for the optimization algorithm to find the MLE. Another way to give the likelihood a hand is to augment it with a (weakly) informative prior and do Bayesian estimation. This approach is most applicable if we have domain information to help us formulate a useful prior. I'll illustrate one Bayesian solution to the $t$ distribution fitting problem in the setting where @kjetilbhalvorsen demonstrates that the MLE approach fails: sample size $n = 10$, location $\mu = 0$, scale $\sigma = 1$ and degrees of freedom $\nu = 2.5$. I'll use the brms package to do the Bayesian model fitting and two different priors for the degrees of freedom $\nu$: strongly informative prior: $\nu \sim \operatorname{Gamma}(1, 0.3)$ and informative prior: $\nu \sim \operatorname{Gamma}(1, 0.1)$, with the constraint $\nu > 1$ (otherwise the mean of the $t$ distribution is undefined.) Both choices indicate there is high prior probability the degrees of freedom are less than 5: under the informative prior, $\operatorname{Pr}(\nu<5) = 0.33$ and under the strongly informative prior, $\operatorname{Pr}(\nu<5) = 0.7$. So both priors are quite "opinionated", which we would like to avoid in general. [The default brms prior on the degrees of freedom is $\operatorname{Gamma}(2, 0.1)$.] On the other hand, in general we would also probably collect more than $n = 10$ observations for a study where we know there is a lot of variability in the outcome. And here is how to do Bayesian $t$ distribution fitting with brms::brm. First we simulate a sample of size $n$ from $t(\mu=0,\sigma=1,\nu=2.5)$ where $\mu$ is the location, $\sigma$ is the scale and $\nu$ are the degrees of freedom. n <- 10 mu <- 0 sigma <- 1 nu <- 2.5 x <- rt(n, nu) * sigma + mu Then we fit an intercept-only $t$-family model. fit.brm <- brm( x ~ 1, family = student, data = data.frame(x), prior = c( prior(student_t(3, 0, 2.5), class = "Intercept"), prior(student_t(3, 0, 2.5), class = "sigma"), prior(gamma(1, 0.3), class = "nu") ) ) While the posterior distributions of the location $\mu$ and scale $\sigma$ are reasonably symmetric, the posterior of the degrees of freedom $\nu$ is very skewed. So I will use the posterior mode (rather than the posterior mean or the posterior median) to estimate the parameters. round( apply(posterior, 2, mode), 3 ) #> μ σ ν #> 0.161 0.785 2.164 And finally, I repeat the three analyses (MLE, Bayesian with weakly informative prior, Bayesian with informative prior) 200 times. Each analysis estimates all three parameters (location $\mu$, scale $\sigma$ and degrees of freedom $\nu$) but below I plot histograms of the estimated degrees of freedom only. The true $\nu$ is 2.5. Maximum likelihood estimation fails dramatically more than half of the time (100 is the upper bound for $\nu$ in the optimization). Bayesian estimation doesn't fail in any of the 200 simulations but the estimate is biased upwards unless the prior information indicates strongly that we expect a priori only a few degrees of freedom.
Fitting t-distribution in R: scaling parameter
@SergeyBushmanov points out that sometimes you need to give maximum likelihood estimation a hand by providing appropriate starting point and lower/upper bounds for the optimization algorithm to find t
Fitting t-distribution in R: scaling parameter @SergeyBushmanov points out that sometimes you need to give maximum likelihood estimation a hand by providing appropriate starting point and lower/upper bounds for the optimization algorithm to find the MLE. Another way to give the likelihood a hand is to augment it with a (weakly) informative prior and do Bayesian estimation. This approach is most applicable if we have domain information to help us formulate a useful prior. I'll illustrate one Bayesian solution to the $t$ distribution fitting problem in the setting where @kjetilbhalvorsen demonstrates that the MLE approach fails: sample size $n = 10$, location $\mu = 0$, scale $\sigma = 1$ and degrees of freedom $\nu = 2.5$. I'll use the brms package to do the Bayesian model fitting and two different priors for the degrees of freedom $\nu$: strongly informative prior: $\nu \sim \operatorname{Gamma}(1, 0.3)$ and informative prior: $\nu \sim \operatorname{Gamma}(1, 0.1)$, with the constraint $\nu > 1$ (otherwise the mean of the $t$ distribution is undefined.) Both choices indicate there is high prior probability the degrees of freedom are less than 5: under the informative prior, $\operatorname{Pr}(\nu<5) = 0.33$ and under the strongly informative prior, $\operatorname{Pr}(\nu<5) = 0.7$. So both priors are quite "opinionated", which we would like to avoid in general. [The default brms prior on the degrees of freedom is $\operatorname{Gamma}(2, 0.1)$.] On the other hand, in general we would also probably collect more than $n = 10$ observations for a study where we know there is a lot of variability in the outcome. And here is how to do Bayesian $t$ distribution fitting with brms::brm. First we simulate a sample of size $n$ from $t(\mu=0,\sigma=1,\nu=2.5)$ where $\mu$ is the location, $\sigma$ is the scale and $\nu$ are the degrees of freedom. n <- 10 mu <- 0 sigma <- 1 nu <- 2.5 x <- rt(n, nu) * sigma + mu Then we fit an intercept-only $t$-family model. fit.brm <- brm( x ~ 1, family = student, data = data.frame(x), prior = c( prior(student_t(3, 0, 2.5), class = "Intercept"), prior(student_t(3, 0, 2.5), class = "sigma"), prior(gamma(1, 0.3), class = "nu") ) ) While the posterior distributions of the location $\mu$ and scale $\sigma$ are reasonably symmetric, the posterior of the degrees of freedom $\nu$ is very skewed. So I will use the posterior mode (rather than the posterior mean or the posterior median) to estimate the parameters. round( apply(posterior, 2, mode), 3 ) #> μ σ ν #> 0.161 0.785 2.164 And finally, I repeat the three analyses (MLE, Bayesian with weakly informative prior, Bayesian with informative prior) 200 times. Each analysis estimates all three parameters (location $\mu$, scale $\sigma$ and degrees of freedom $\nu$) but below I plot histograms of the estimated degrees of freedom only. The true $\nu$ is 2.5. Maximum likelihood estimation fails dramatically more than half of the time (100 is the upper bound for $\nu$ in the optimization). Bayesian estimation doesn't fail in any of the 200 simulations but the estimate is biased upwards unless the prior information indicates strongly that we expect a priori only a few degrees of freedom.
Fitting t-distribution in R: scaling parameter @SergeyBushmanov points out that sometimes you need to give maximum likelihood estimation a hand by providing appropriate starting point and lower/upper bounds for the optimization algorithm to find t
13,021
Can I simply remove one of two predictor variables that are highly linearly correlated?
Both B and E are derived from V. B and E are clearly not truly "independent" variables from each other. The underlying variable that really matters here is V. You should probably disgard both B and E in this case and keep V only. In a more general situation, when you have two independent variables that are very highly correlated, you definitely should remove one of them because you run into the multicollinearity conundrum and your regression model's regression coefficients related to the two highly correlated variables will be unreliable. Also, in plain English if two variables are so highly correlated they will obviously impart nearly exactly the same information to your regression model. But, by including both you are actually weakening the model. You are not adding incremental information. Instead, you are infusing your model with noise. Not a good thing. One way you could keep highly correlated variables within your model is to use instead of regression a Principal Component Analysis (PCA) model. PCA models are made to get rid off multicollinearity. The trade off is that you end up with two or three principal components within your model that are often just mathematical constructs and are pretty much incomprehensible in logical terms. PCA is therefore frequently abandoned as a method whenever you have to present your results to an outside audience such as management, regulators, etc... PCA models create cryptic black boxes that are very challenging to explain.
Can I simply remove one of two predictor variables that are highly linearly correlated?
Both B and E are derived from V. B and E are clearly not truly "independent" variables from each other. The underlying variable that really matters here is V. You should probably disgard both B and
Can I simply remove one of two predictor variables that are highly linearly correlated? Both B and E are derived from V. B and E are clearly not truly "independent" variables from each other. The underlying variable that really matters here is V. You should probably disgard both B and E in this case and keep V only. In a more general situation, when you have two independent variables that are very highly correlated, you definitely should remove one of them because you run into the multicollinearity conundrum and your regression model's regression coefficients related to the two highly correlated variables will be unreliable. Also, in plain English if two variables are so highly correlated they will obviously impart nearly exactly the same information to your regression model. But, by including both you are actually weakening the model. You are not adding incremental information. Instead, you are infusing your model with noise. Not a good thing. One way you could keep highly correlated variables within your model is to use instead of regression a Principal Component Analysis (PCA) model. PCA models are made to get rid off multicollinearity. The trade off is that you end up with two or three principal components within your model that are often just mathematical constructs and are pretty much incomprehensible in logical terms. PCA is therefore frequently abandoned as a method whenever you have to present your results to an outside audience such as management, regulators, etc... PCA models create cryptic black boxes that are very challenging to explain.
Can I simply remove one of two predictor variables that are highly linearly correlated? Both B and E are derived from V. B and E are clearly not truly "independent" variables from each other. The underlying variable that really matters here is V. You should probably disgard both B and
13,022
Can I simply remove one of two predictor variables that are highly linearly correlated?
Here is an answer from the point of view of a machine learner, although I am afraid that I'll be beaten by real statisticians for it. Is it possible for me to just "throw away" one of the variables? Well, the question is what type of model you want to use for prediction. It depends e.g. on ... can the model with correlated predictors ? E.g. although NaiveBayes theoretically has problems with correlated variables, experiments have shown that it still can perform well. how does the model process the predictor variables ? E.g. the difference between B and V will be normalized out in a probability density estimation, maybe the same for E and V depending on the variance of D (as euphoria already said) which usage combination of B and E (one, none, both) delivers the best result, estimated by a mindful crossvalidation + a test on a holdout set ? Sometimes we machine learners even perform genetic optimization to find the best arithmetic combination of a set of predictors.
Can I simply remove one of two predictor variables that are highly linearly correlated?
Here is an answer from the point of view of a machine learner, although I am afraid that I'll be beaten by real statisticians for it. Is it possible for me to just "throw away" one of the variables? W
Can I simply remove one of two predictor variables that are highly linearly correlated? Here is an answer from the point of view of a machine learner, although I am afraid that I'll be beaten by real statisticians for it. Is it possible for me to just "throw away" one of the variables? Well, the question is what type of model you want to use for prediction. It depends e.g. on ... can the model with correlated predictors ? E.g. although NaiveBayes theoretically has problems with correlated variables, experiments have shown that it still can perform well. how does the model process the predictor variables ? E.g. the difference between B and V will be normalized out in a probability density estimation, maybe the same for E and V depending on the variance of D (as euphoria already said) which usage combination of B and E (one, none, both) delivers the best result, estimated by a mindful crossvalidation + a test on a holdout set ? Sometimes we machine learners even perform genetic optimization to find the best arithmetic combination of a set of predictors.
Can I simply remove one of two predictor variables that are highly linearly correlated? Here is an answer from the point of view of a machine learner, although I am afraid that I'll be beaten by real statisticians for it. Is it possible for me to just "throw away" one of the variables? W
13,023
Can I simply remove one of two predictor variables that are highly linearly correlated?
B is a linear transform of V. E represents an interaction between V and D. Have you considered specifying a model that is Y = Intercept + V + D + V:D? As @euphoria83 suggests, it seems likely that there is little variation in D, so it may not solve your problem; however it should at least make the independent contributions of V and D clear. Be sure to center both V and D beforehand.
Can I simply remove one of two predictor variables that are highly linearly correlated?
B is a linear transform of V. E represents an interaction between V and D. Have you considered specifying a model that is Y = Intercept + V + D + V:D? As @euphoria83 suggests, it seems likely that t
Can I simply remove one of two predictor variables that are highly linearly correlated? B is a linear transform of V. E represents an interaction between V and D. Have you considered specifying a model that is Y = Intercept + V + D + V:D? As @euphoria83 suggests, it seems likely that there is little variation in D, so it may not solve your problem; however it should at least make the independent contributions of V and D clear. Be sure to center both V and D beforehand.
Can I simply remove one of two predictor variables that are highly linearly correlated? B is a linear transform of V. E represents an interaction between V and D. Have you considered specifying a model that is Y = Intercept + V + D + V:D? As @euphoria83 suggests, it seems likely that t
13,024
Can I simply remove one of two predictor variables that are highly linearly correlated?
If D is not a constant, then B and E are effectively two different variables because of the variations in D. The high correlation indicates that D is practically constant throughout the training data. If that is the case, then you can discard either B or E.
Can I simply remove one of two predictor variables that are highly linearly correlated?
If D is not a constant, then B and E are effectively two different variables because of the variations in D. The high correlation indicates that D is practically constant throughout the training data.
Can I simply remove one of two predictor variables that are highly linearly correlated? If D is not a constant, then B and E are effectively two different variables because of the variations in D. The high correlation indicates that D is practically constant throughout the training data. If that is the case, then you can discard either B or E.
Can I simply remove one of two predictor variables that are highly linearly correlated? If D is not a constant, then B and E are effectively two different variables because of the variations in D. The high correlation indicates that D is practically constant throughout the training data.
13,025
What are the mathematically rigorous data augmentation techniques?
The reason you "wish you had a million observations" is typically because you want to use the data to to infer something that you don't already know. For example, you might want to fit a model, or make predictions. In this context, the data processing inequality implies that, unfortunately, simulating additional data is less helpful than one might hope (but this doesn't mean it's useless). To be more specific, let $Y$ be a random vector representing unknown quantities we'd like to learn about, and let $X$ be a random vector representing the data. Now, suppose we simulate new data using knowledge learned from the original data. For example, we might fit a probability distribution to the original data and then sample from it. Let $\tilde{X}$ be a random vector representing the simulated data, and $Z = [X, \tilde{X}]$ represent the augmented dataset. Because $Z$ was generated based on $X$, we have that $Z$ and $Y$ are conditionally independent, given $X$. That is: $$p(x,y,z) = p(x,y) p(z \mid x)$$ According to the data processing inequality, the mutual information between $Z$ and $Y$ can't exceed that between $X$ and $Y$: $$I(Z; Y) \le I(X; Y)$$ Since $Z$ contains $X$, this is actually an equality. In any case, this says that, no matter how we try to process the data--including using it to simulate new data)--it's impossible to gain additional information about our quantity of interest (beyond that already contained in the original data). But, here's an interesting caveat. Note that the above result holds when $\tilde{X}$ is generated based on $X$. If $\tilde{X}$ is also based on some external source $S$, then it may be possible to gain additional information about $Y$ (if $S$ carries this information). Given the above, it's interesting to note that data augmentation can work well in practice. For example, as Haitao Du mentioned, when training an image classifier, randomly transformed copies of the training images are sometimes used (e.g. translations, reflections, and various distortions). This encourages the learning algorithm to find a classifier that's invariant to these transformations, thereby increasing performance. Why does this work? Essentially, we're introducing a useful inductive bias (similar in effect to a Bayesian prior). We know a priori that the true function ought to be invariant, and the augmented images are a way of imposing this knowledge. From another perspective, this a priori knowledge is the additional source $S$ that I mentioned above.
What are the mathematically rigorous data augmentation techniques?
The reason you "wish you had a million observations" is typically because you want to use the data to to infer something that you don't already know. For example, you might want to fit a model, or mak
What are the mathematically rigorous data augmentation techniques? The reason you "wish you had a million observations" is typically because you want to use the data to to infer something that you don't already know. For example, you might want to fit a model, or make predictions. In this context, the data processing inequality implies that, unfortunately, simulating additional data is less helpful than one might hope (but this doesn't mean it's useless). To be more specific, let $Y$ be a random vector representing unknown quantities we'd like to learn about, and let $X$ be a random vector representing the data. Now, suppose we simulate new data using knowledge learned from the original data. For example, we might fit a probability distribution to the original data and then sample from it. Let $\tilde{X}$ be a random vector representing the simulated data, and $Z = [X, \tilde{X}]$ represent the augmented dataset. Because $Z$ was generated based on $X$, we have that $Z$ and $Y$ are conditionally independent, given $X$. That is: $$p(x,y,z) = p(x,y) p(z \mid x)$$ According to the data processing inequality, the mutual information between $Z$ and $Y$ can't exceed that between $X$ and $Y$: $$I(Z; Y) \le I(X; Y)$$ Since $Z$ contains $X$, this is actually an equality. In any case, this says that, no matter how we try to process the data--including using it to simulate new data)--it's impossible to gain additional information about our quantity of interest (beyond that already contained in the original data). But, here's an interesting caveat. Note that the above result holds when $\tilde{X}$ is generated based on $X$. If $\tilde{X}$ is also based on some external source $S$, then it may be possible to gain additional information about $Y$ (if $S$ carries this information). Given the above, it's interesting to note that data augmentation can work well in practice. For example, as Haitao Du mentioned, when training an image classifier, randomly transformed copies of the training images are sometimes used (e.g. translations, reflections, and various distortions). This encourages the learning algorithm to find a classifier that's invariant to these transformations, thereby increasing performance. Why does this work? Essentially, we're introducing a useful inductive bias (similar in effect to a Bayesian prior). We know a priori that the true function ought to be invariant, and the augmented images are a way of imposing this knowledge. From another perspective, this a priori knowledge is the additional source $S$ that I mentioned above.
What are the mathematically rigorous data augmentation techniques? The reason you "wish you had a million observations" is typically because you want to use the data to to infer something that you don't already know. For example, you might want to fit a model, or mak
13,026
What are the mathematically rigorous data augmentation techniques?
Are there any proofs that describe the most mathematically precise way to do this? Any transformation would have some math behind it. However, I do think image data augmentation would depend on the specific use case / domain knowledge in specific field. For example, if we want to detect dog or cat, we can flip images for augmentation. This is because we know an upside down dog is still a dog. On the other hand, if we are doing digits recognition, flip images upside down may be not a good way because 6 and 9 are different digits. For other domain, say computer vision on medical image, I do not know if flip/mirror on images will make since on chest X ray. Therefore, it is domain specific and may not captured by some general math model.
What are the mathematically rigorous data augmentation techniques?
Are there any proofs that describe the most mathematically precise way to do this? Any transformation would have some math behind it. However, I do think image data augmentation would depend on the
What are the mathematically rigorous data augmentation techniques? Are there any proofs that describe the most mathematically precise way to do this? Any transformation would have some math behind it. However, I do think image data augmentation would depend on the specific use case / domain knowledge in specific field. For example, if we want to detect dog or cat, we can flip images for augmentation. This is because we know an upside down dog is still a dog. On the other hand, if we are doing digits recognition, flip images upside down may be not a good way because 6 and 9 are different digits. For other domain, say computer vision on medical image, I do not know if flip/mirror on images will make since on chest X ray. Therefore, it is domain specific and may not captured by some general math model.
What are the mathematically rigorous data augmentation techniques? Are there any proofs that describe the most mathematically precise way to do this? Any transformation would have some math behind it. However, I do think image data augmentation would depend on the
13,027
What are the mathematically rigorous data augmentation techniques?
The question is, why do you want to do data augmentation? Of course, more data is better, but your augmented dataset is redundant: your million augmented data points are not as good as a million actual data points. An alternative way of thinking of data augmentation is in terms of teaching invariances. For example, CNNs in deep learning are translationally invariant, which is a good thing for image recognition. Unfortunately, we would wish they were invariant to rotations as well (a leaning cat is still a cat), which is not easy to do within the architecture. In summary: Data augmentation is a way to create a model that is roughly invariant with respect to a set of transformations when you cannot force that invariance elsewhere (be it the features or the model). Answering your question, the only way to determine the valid data augmentation procedures is to apply domain knowledge. How can your data points be perturbed or modified without substantially changing them? What do you want your model to learn to ignore? Let me prove that there is no general way, and there cannot be one. Consider the case of predicting the position of an object at $t=1$ given that your $(x, y)$ are the initial positions. A logical data augmentation scheme would be to displace the points microscopically, surely they will end up almost at the same position, right? But if the system is chaotic (for example, a double pendulum), the microscopical deviations would produce exponentially diverging trajectories. What data augmentation can you apply there? Maybe perturbations of the points that lie in large basins of attractions. That would bias your data since you will have fewer samples for the chaotic regimes (which is not necessarily a bad thing!). In any case, any perturbation scheme you come up with will come from a careful analysis of the problem at hand.
What are the mathematically rigorous data augmentation techniques?
The question is, why do you want to do data augmentation? Of course, more data is better, but your augmented dataset is redundant: your million augmented data points are not as good as a million actua
What are the mathematically rigorous data augmentation techniques? The question is, why do you want to do data augmentation? Of course, more data is better, but your augmented dataset is redundant: your million augmented data points are not as good as a million actual data points. An alternative way of thinking of data augmentation is in terms of teaching invariances. For example, CNNs in deep learning are translationally invariant, which is a good thing for image recognition. Unfortunately, we would wish they were invariant to rotations as well (a leaning cat is still a cat), which is not easy to do within the architecture. In summary: Data augmentation is a way to create a model that is roughly invariant with respect to a set of transformations when you cannot force that invariance elsewhere (be it the features or the model). Answering your question, the only way to determine the valid data augmentation procedures is to apply domain knowledge. How can your data points be perturbed or modified without substantially changing them? What do you want your model to learn to ignore? Let me prove that there is no general way, and there cannot be one. Consider the case of predicting the position of an object at $t=1$ given that your $(x, y)$ are the initial positions. A logical data augmentation scheme would be to displace the points microscopically, surely they will end up almost at the same position, right? But if the system is chaotic (for example, a double pendulum), the microscopical deviations would produce exponentially diverging trajectories. What data augmentation can you apply there? Maybe perturbations of the points that lie in large basins of attractions. That would bias your data since you will have fewer samples for the chaotic regimes (which is not necessarily a bad thing!). In any case, any perturbation scheme you come up with will come from a careful analysis of the problem at hand.
What are the mathematically rigorous data augmentation techniques? The question is, why do you want to do data augmentation? Of course, more data is better, but your augmented dataset is redundant: your million augmented data points are not as good as a million actua
13,028
How to understand the drawbacks of Hierarchical Clustering?
Whereas $k$-means tries to optimize a global goal (variance of the clusters) and achieves a local optimum, agglomerative hierarchical clustering aims at finding the best step at each cluster fusion (greedy algorithm) which is done exactly but resulting in a potentially suboptimal solution. One should use hierarchical clustering when underlying data has a hierarchical structure (like the correlations in financial markets) and you want to recover the hierarchy. You can still apply $k$-means to do that, but you may end up with partitions (from the coarsest one (all data points in a cluster) to the finest one (each data point is a cluster)) that are not nested and thus not a proper hierarchy. If you want to dig into finer properties of clustering, you may not want to oppose flat clustering such as $k$-means to hierarchical clustering such as the Single, Average, Complete Linkages. For instance, all these clustering are space-conserving, i.e. when you are building clusters you do not distort the space, whereas a hierarchical clustering such as Ward is not space-conserving, i.e. at each merging step it will distort the metric space. To conclude, the drawbacks of the hierarchical clustering algorithms can be very different from one to another. Some may share similar properties to $k$-means: Ward aims at optimizing variance, but Single Linkage not. But they can also have different properties: Ward is space-dilating, whereas Single Linkage is space-conserving like $k$-means. -- edit to precise the space-conserving and space-dilating properties Space-conserving: $$D_{ij} \in \left[ \min_{x \in C_i, y \in C_j} d(x,y), \max_{x \in C_i, y \in C_j} d(x,y) \right]$$ where $D_{ij}$ is the distance between clusters $C_i$ and $C_j$ you want to merge, and $d$ is the distance between datapoints. Space-dilating: $$D(C_i \cup C_j, C_k) \geq \max(D_{ik}, D_{jk}),$$ i.e. by merging $C_i$ and $C_j$ the algorithm will push further away the cluster $C_k$.
How to understand the drawbacks of Hierarchical Clustering?
Whereas $k$-means tries to optimize a global goal (variance of the clusters) and achieves a local optimum, agglomerative hierarchical clustering aims at finding the best step at each cluster fusion (g
How to understand the drawbacks of Hierarchical Clustering? Whereas $k$-means tries to optimize a global goal (variance of the clusters) and achieves a local optimum, agglomerative hierarchical clustering aims at finding the best step at each cluster fusion (greedy algorithm) which is done exactly but resulting in a potentially suboptimal solution. One should use hierarchical clustering when underlying data has a hierarchical structure (like the correlations in financial markets) and you want to recover the hierarchy. You can still apply $k$-means to do that, but you may end up with partitions (from the coarsest one (all data points in a cluster) to the finest one (each data point is a cluster)) that are not nested and thus not a proper hierarchy. If you want to dig into finer properties of clustering, you may not want to oppose flat clustering such as $k$-means to hierarchical clustering such as the Single, Average, Complete Linkages. For instance, all these clustering are space-conserving, i.e. when you are building clusters you do not distort the space, whereas a hierarchical clustering such as Ward is not space-conserving, i.e. at each merging step it will distort the metric space. To conclude, the drawbacks of the hierarchical clustering algorithms can be very different from one to another. Some may share similar properties to $k$-means: Ward aims at optimizing variance, but Single Linkage not. But they can also have different properties: Ward is space-dilating, whereas Single Linkage is space-conserving like $k$-means. -- edit to precise the space-conserving and space-dilating properties Space-conserving: $$D_{ij} \in \left[ \min_{x \in C_i, y \in C_j} d(x,y), \max_{x \in C_i, y \in C_j} d(x,y) \right]$$ where $D_{ij}$ is the distance between clusters $C_i$ and $C_j$ you want to merge, and $d$ is the distance between datapoints. Space-dilating: $$D(C_i \cup C_j, C_k) \geq \max(D_{ik}, D_{jk}),$$ i.e. by merging $C_i$ and $C_j$ the algorithm will push further away the cluster $C_k$.
How to understand the drawbacks of Hierarchical Clustering? Whereas $k$-means tries to optimize a global goal (variance of the clusters) and achieves a local optimum, agglomerative hierarchical clustering aims at finding the best step at each cluster fusion (g
13,029
How to understand the drawbacks of Hierarchical Clustering?
Scalability $k$ means is the clear winner here. $O(n\cdot k\cdot d\cdot i)$ is much better than the $O(n^3 d)$ (in a few cases $O(n^2 d)$) scalability of hierarchical clustering because usually both $k$ and $i$ and $d$ are small (unfortunately, $i$ tends to grow with $n$, so $O(n)$ does not usually hold). Also, memory consumption is linear, as opposed to quadratic (usually, linear special cases exist). Flexibility $k$-means is extremely limited in applicability. It is essentially limited to Euclidean distances (including Euclidean in kernel spaces, and Bregman divergences, but these are quite exotic and nobody actually uses them with $k$-means). Even worse, $k$-means only works on numerical data (which should actually be continuous and dense to be a good fit for $k$-means). Hierarchical clustering is the clear winner here. It does not even require a distance - any measure can be used, including similarity functions simply by preferring high values to low values. Categorial data? sure just use e.g. Jaccard. Strings? Try Levenshtein distance. Time series? sure. Mixed type data? Gower distance. There are millions of data sets where you can use hierarchical clustering, but where you cannot use $k$-means. Model No winner here. $k$-means scores high because it yields a great data reduction. Centroids are easy to understand and use. Hierarchical clustering, on the other hand, produces a dendrogram. A dendrogram can also be very very useful in understanding your data set.
How to understand the drawbacks of Hierarchical Clustering?
Scalability $k$ means is the clear winner here. $O(n\cdot k\cdot d\cdot i)$ is much better than the $O(n^3 d)$ (in a few cases $O(n^2 d)$) scalability of hierarchical clustering because usually both $
How to understand the drawbacks of Hierarchical Clustering? Scalability $k$ means is the clear winner here. $O(n\cdot k\cdot d\cdot i)$ is much better than the $O(n^3 d)$ (in a few cases $O(n^2 d)$) scalability of hierarchical clustering because usually both $k$ and $i$ and $d$ are small (unfortunately, $i$ tends to grow with $n$, so $O(n)$ does not usually hold). Also, memory consumption is linear, as opposed to quadratic (usually, linear special cases exist). Flexibility $k$-means is extremely limited in applicability. It is essentially limited to Euclidean distances (including Euclidean in kernel spaces, and Bregman divergences, but these are quite exotic and nobody actually uses them with $k$-means). Even worse, $k$-means only works on numerical data (which should actually be continuous and dense to be a good fit for $k$-means). Hierarchical clustering is the clear winner here. It does not even require a distance - any measure can be used, including similarity functions simply by preferring high values to low values. Categorial data? sure just use e.g. Jaccard. Strings? Try Levenshtein distance. Time series? sure. Mixed type data? Gower distance. There are millions of data sets where you can use hierarchical clustering, but where you cannot use $k$-means. Model No winner here. $k$-means scores high because it yields a great data reduction. Centroids are easy to understand and use. Hierarchical clustering, on the other hand, produces a dendrogram. A dendrogram can also be very very useful in understanding your data set.
How to understand the drawbacks of Hierarchical Clustering? Scalability $k$ means is the clear winner here. $O(n\cdot k\cdot d\cdot i)$ is much better than the $O(n^3 d)$ (in a few cases $O(n^2 d)$) scalability of hierarchical clustering because usually both $
13,030
How to understand the drawbacks of Hierarchical Clustering?
I just wanted to add to the other answers a bit about how, in some sense, there is a strong theoretical reason to prefer certain hierarchical clustering methods. A common assumption in cluster analysis is that the data are sampled from some underlying probability density $f$ that we don't have access to. But suppose we had access to it. How would we define the clusters of $f$? A very natural and intuitive approach is to say that the clusters of $f$ are the regions of high density. For example, consider the two-peaked density below: By drawing a line across the graph we induce a set of clusters. For instance, if we draw a line at $\lambda_1$, we get the two clusters shown. But if we draw the line at $\lambda_3$, we get a single cluster. To make this more precise, suppose we have an arbitrary $\lambda > 0$. What are the clusters of $f$ at level $\lambda$? They are the connected component of the superlevel set $\{x : f(x) \geq \lambda \}$. Now instead of picking an arbitrary $\lambda$ we might consider all $\lambda$, such that the set of "true" clusters of $f$ are all connected components of any superlevel set of $f$. The key is that this collection of clusters has hierarchical structure. Let me make that more precise. Suppose $f$ is supported on $\mathcal X$. Now let $C_1$ be a connected component of $\{ x : f(x) \geq \lambda_1 \}$, and $C_2$ be a connected component of $\{ x : f(x) \geq \lambda_2 \}$. In other words, $C_1$ is a cluster at level $\lambda_1$, and $C_2$ is a cluster at level $\lambda_2$. Then if $\lambda_2 < \lambda_1$, then either $C_1 \subset C_2$, or $C_1 \cap C_2 = \emptyset$. This nesting relationship holds for any pair of clusters in our collection, so what we have is in fact a hierarchy of clusters. We call this the cluster tree. So now I have some data sampled from a density. Can I cluster this data in a way that recovers the cluster tree? In particular, we'd like a method to be consistent in the sense that as we gather more and more data, our empirical estimate of the cluster tree grows closer and closer to the true cluster tree. Hartigan was the first to ask such questions, and in doing so he defined precisely what it would mean for a hierarchical clustering method to consistently estimate the cluster tree. His definition was as follows: Let $A$ and $B$ be true disjoint clusters of $f$ as defined above -- that is, they are connected components of some superlevel sets. Now draw a set of $n$ samples iid from $f$, and call this set $X_n$. We apply a hierarchical clustering method to the data $X_n$, and we get back a collection of empirical clusters. Let $A_n$ be the smallest empirical cluster containing all of $A \cap X_n$, and let $B_n$ be the smallest containing all of $B \cap X_n$. Then our clustering method is said to be Hartigan consistent if $\Pr(A_n \cap B_n) = \emptyset \to 1$ as $n \to \infty$ for any pair of disjoint clusters $A$ and $B$. Essentially, Hartigan consistency says that our clustering method should adequately separate regions of high density. Hartigan investigated whether single linkage clustering might be consistent, and found that it is not consistent in dimensions > 1. The problem of finding a general, consistent method for estimating the cluster tree was open until just a few years ago, when Chaudhuri and Dasgupta introduced robust single linkage, which is provably consistent. I'd suggest reading about their method, as it is quite elegant, in my opinion. So, to address your questions, there is a sense in which hierarchical cluster is the "right" thing to do when attempting to recover the structure of a density. However, note the scare-quotes around "right"... Ultimately density-based clustering methods tend to perform poorly in high dimensions due to the curse of dimensionality, and so even though a definition of clustering based on clusters being regions of high probability is quite clean and intuitive, it often is ignored in favor of methods which perform better in practice. That isn't to say robust single linkage isn't practical -- it actually works quite well on problems in lower dimensions. Lastly, I'll say that Hartigan consistency is in some sense not in accordance with our intuition of convergence. The problem is that Hartigan consistency allows a clustering method to greatly over-segment clusters such that an algorithm may be Hartigan consistent, yet produce clusterings which are very different than the true cluster tree. We have produced work this year on an alternative notion of convergence which addresses these issues. The work appeared in "Beyond Hartigan Consistency: Merge distortion metric for hierarchical clustering" in COLT 2015.
How to understand the drawbacks of Hierarchical Clustering?
I just wanted to add to the other answers a bit about how, in some sense, there is a strong theoretical reason to prefer certain hierarchical clustering methods. A common assumption in cluster analysi
How to understand the drawbacks of Hierarchical Clustering? I just wanted to add to the other answers a bit about how, in some sense, there is a strong theoretical reason to prefer certain hierarchical clustering methods. A common assumption in cluster analysis is that the data are sampled from some underlying probability density $f$ that we don't have access to. But suppose we had access to it. How would we define the clusters of $f$? A very natural and intuitive approach is to say that the clusters of $f$ are the regions of high density. For example, consider the two-peaked density below: By drawing a line across the graph we induce a set of clusters. For instance, if we draw a line at $\lambda_1$, we get the two clusters shown. But if we draw the line at $\lambda_3$, we get a single cluster. To make this more precise, suppose we have an arbitrary $\lambda > 0$. What are the clusters of $f$ at level $\lambda$? They are the connected component of the superlevel set $\{x : f(x) \geq \lambda \}$. Now instead of picking an arbitrary $\lambda$ we might consider all $\lambda$, such that the set of "true" clusters of $f$ are all connected components of any superlevel set of $f$. The key is that this collection of clusters has hierarchical structure. Let me make that more precise. Suppose $f$ is supported on $\mathcal X$. Now let $C_1$ be a connected component of $\{ x : f(x) \geq \lambda_1 \}$, and $C_2$ be a connected component of $\{ x : f(x) \geq \lambda_2 \}$. In other words, $C_1$ is a cluster at level $\lambda_1$, and $C_2$ is a cluster at level $\lambda_2$. Then if $\lambda_2 < \lambda_1$, then either $C_1 \subset C_2$, or $C_1 \cap C_2 = \emptyset$. This nesting relationship holds for any pair of clusters in our collection, so what we have is in fact a hierarchy of clusters. We call this the cluster tree. So now I have some data sampled from a density. Can I cluster this data in a way that recovers the cluster tree? In particular, we'd like a method to be consistent in the sense that as we gather more and more data, our empirical estimate of the cluster tree grows closer and closer to the true cluster tree. Hartigan was the first to ask such questions, and in doing so he defined precisely what it would mean for a hierarchical clustering method to consistently estimate the cluster tree. His definition was as follows: Let $A$ and $B$ be true disjoint clusters of $f$ as defined above -- that is, they are connected components of some superlevel sets. Now draw a set of $n$ samples iid from $f$, and call this set $X_n$. We apply a hierarchical clustering method to the data $X_n$, and we get back a collection of empirical clusters. Let $A_n$ be the smallest empirical cluster containing all of $A \cap X_n$, and let $B_n$ be the smallest containing all of $B \cap X_n$. Then our clustering method is said to be Hartigan consistent if $\Pr(A_n \cap B_n) = \emptyset \to 1$ as $n \to \infty$ for any pair of disjoint clusters $A$ and $B$. Essentially, Hartigan consistency says that our clustering method should adequately separate regions of high density. Hartigan investigated whether single linkage clustering might be consistent, and found that it is not consistent in dimensions > 1. The problem of finding a general, consistent method for estimating the cluster tree was open until just a few years ago, when Chaudhuri and Dasgupta introduced robust single linkage, which is provably consistent. I'd suggest reading about their method, as it is quite elegant, in my opinion. So, to address your questions, there is a sense in which hierarchical cluster is the "right" thing to do when attempting to recover the structure of a density. However, note the scare-quotes around "right"... Ultimately density-based clustering methods tend to perform poorly in high dimensions due to the curse of dimensionality, and so even though a definition of clustering based on clusters being regions of high probability is quite clean and intuitive, it often is ignored in favor of methods which perform better in practice. That isn't to say robust single linkage isn't practical -- it actually works quite well on problems in lower dimensions. Lastly, I'll say that Hartigan consistency is in some sense not in accordance with our intuition of convergence. The problem is that Hartigan consistency allows a clustering method to greatly over-segment clusters such that an algorithm may be Hartigan consistent, yet produce clusterings which are very different than the true cluster tree. We have produced work this year on an alternative notion of convergence which addresses these issues. The work appeared in "Beyond Hartigan Consistency: Merge distortion metric for hierarchical clustering" in COLT 2015.
How to understand the drawbacks of Hierarchical Clustering? I just wanted to add to the other answers a bit about how, in some sense, there is a strong theoretical reason to prefer certain hierarchical clustering methods. A common assumption in cluster analysi
13,031
How to understand the drawbacks of Hierarchical Clustering?
An additional practical advantage in hierarchical clustering is the possibility of visualising results using dendrogram. If you don't know in advance what number of clusters you're looking for (as is often the case...), you can the dendrogram plot can help you choose $k$ with no need to create separate clusterings. Dedrogram can also give a great insight into data structure, help identify outliers etc. Hierarchical clustering is also deterministic, whereas k-means with random initialization can give you different results when run several times on the same data. In k-means, you also can choose different methods for updating cluster means (although the Hartigan-Wong approach is by far the most common), which is no issue with hierarchical method. EDIT thanks to ttnphns: One feature that hierarchical clustering shares with many other algorithms is the need to choose a distance measure. This is often highly dependent on the particular application and goals. This might be seen as an additional complication (another parameter to select...), but also as an asset - more possibilities. On the contrary, classical K-means algorithm specifically uses Euclidean distance.
How to understand the drawbacks of Hierarchical Clustering?
An additional practical advantage in hierarchical clustering is the possibility of visualising results using dendrogram. If you don't know in advance what number of clusters you're looking for (as is
How to understand the drawbacks of Hierarchical Clustering? An additional practical advantage in hierarchical clustering is the possibility of visualising results using dendrogram. If you don't know in advance what number of clusters you're looking for (as is often the case...), you can the dendrogram plot can help you choose $k$ with no need to create separate clusterings. Dedrogram can also give a great insight into data structure, help identify outliers etc. Hierarchical clustering is also deterministic, whereas k-means with random initialization can give you different results when run several times on the same data. In k-means, you also can choose different methods for updating cluster means (although the Hartigan-Wong approach is by far the most common), which is no issue with hierarchical method. EDIT thanks to ttnphns: One feature that hierarchical clustering shares with many other algorithms is the need to choose a distance measure. This is often highly dependent on the particular application and goals. This might be seen as an additional complication (another parameter to select...), but also as an asset - more possibilities. On the contrary, classical K-means algorithm specifically uses Euclidean distance.
How to understand the drawbacks of Hierarchical Clustering? An additional practical advantage in hierarchical clustering is the possibility of visualising results using dendrogram. If you don't know in advance what number of clusters you're looking for (as is
13,032
Do the pdf and the pmf and the cdf contain the same information?
Where a distinction is made between probability function and density*, the pmf applies only to discrete random variables, while the pdf applies to continuous random variables. * formal approaches can encompass both and use a single term for them The cdf applies to any random variables, including ones that have neither a pdf nor pmf (such as a mixed distribution - for example, consider the amount of rain in a day, or the amount of money paid in claims on a property insurance policy, either of which might be modelled by a zero-inflated continuous distribution). The cdf for a random variable $X$ gives $P(X\leq x)$ The pmf for a discrete random variable $X$, gives $P(X=x)$. The pdf doesn't itself give probabilities, but relative probabilities; continuous distributions don't have point probabilities. To get probabilities from pdfs you need to integrate over some interval - or take a difference of two cdf values. It's difficult to answer the question 'do they contain the same information' because it depends on what you mean. You can go from pdf to cdf (via integration), and from pmf to cdf (via summation), and from cdf to pdf (via differentiation) and from cdf to pmf (via differencing), so when you have a pmf or a pdf, it contains the same information as the cdf (but in a sense 'encoded' in a different way).
Do the pdf and the pmf and the cdf contain the same information?
Where a distinction is made between probability function and density*, the pmf applies only to discrete random variables, while the pdf applies to continuous random variables. * formal approaches can
Do the pdf and the pmf and the cdf contain the same information? Where a distinction is made between probability function and density*, the pmf applies only to discrete random variables, while the pdf applies to continuous random variables. * formal approaches can encompass both and use a single term for them The cdf applies to any random variables, including ones that have neither a pdf nor pmf (such as a mixed distribution - for example, consider the amount of rain in a day, or the amount of money paid in claims on a property insurance policy, either of which might be modelled by a zero-inflated continuous distribution). The cdf for a random variable $X$ gives $P(X\leq x)$ The pmf for a discrete random variable $X$, gives $P(X=x)$. The pdf doesn't itself give probabilities, but relative probabilities; continuous distributions don't have point probabilities. To get probabilities from pdfs you need to integrate over some interval - or take a difference of two cdf values. It's difficult to answer the question 'do they contain the same information' because it depends on what you mean. You can go from pdf to cdf (via integration), and from pmf to cdf (via summation), and from cdf to pdf (via differentiation) and from cdf to pmf (via differencing), so when you have a pmf or a pdf, it contains the same information as the cdf (but in a sense 'encoded' in a different way).
Do the pdf and the pmf and the cdf contain the same information? Where a distinction is made between probability function and density*, the pmf applies only to discrete random variables, while the pdf applies to continuous random variables. * formal approaches can
13,033
Do the pdf and the pmf and the cdf contain the same information?
PMFs are associated with discrete random variables, PDFs with continuous random variables. For any type of random of random variable, the CDF always exists (and is unique), defined as $$F_X(x) = P\{X \leq x\}.$$ Now, depending on the support set of the random variable $X$, the density (or mass function) need not exist. (Consider the Cantor Set and Cantor Function, the set is recursively defined by removing the center 1/3 of the unit interval, then repeating the procedure for the intervals (0, 1/3) and (2/3, 1), etc. The function is defined as $C(x) = x$, if $x$ is in the Cantor set, and the greatest lower bound in the Cantor Set if $x$ is not a member.) The Cantor Function is a perfectly good distribution function, if you tack on $C(x)= 0$ if $x < 0$ and $C(x) = 1$ if $1 < x$. But this cdf has no density: $C(x)$ is continuous everywhere but its derivative is 0 almost everywhere. No density with respect to any useful measure. So, the answer to your question is, if a density or mass function exists, then it is a derivative of the CDF with respect to some measure. In that sense, they carry the "the same" information. BUT, PDFs and PMFs don't have to exist. CDFs must exist.
Do the pdf and the pmf and the cdf contain the same information?
PMFs are associated with discrete random variables, PDFs with continuous random variables. For any type of random of random variable, the CDF always exists (and is unique), defined as $$F_X(x) = P\{X
Do the pdf and the pmf and the cdf contain the same information? PMFs are associated with discrete random variables, PDFs with continuous random variables. For any type of random of random variable, the CDF always exists (and is unique), defined as $$F_X(x) = P\{X \leq x\}.$$ Now, depending on the support set of the random variable $X$, the density (or mass function) need not exist. (Consider the Cantor Set and Cantor Function, the set is recursively defined by removing the center 1/3 of the unit interval, then repeating the procedure for the intervals (0, 1/3) and (2/3, 1), etc. The function is defined as $C(x) = x$, if $x$ is in the Cantor set, and the greatest lower bound in the Cantor Set if $x$ is not a member.) The Cantor Function is a perfectly good distribution function, if you tack on $C(x)= 0$ if $x < 0$ and $C(x) = 1$ if $1 < x$. But this cdf has no density: $C(x)$ is continuous everywhere but its derivative is 0 almost everywhere. No density with respect to any useful measure. So, the answer to your question is, if a density or mass function exists, then it is a derivative of the CDF with respect to some measure. In that sense, they carry the "the same" information. BUT, PDFs and PMFs don't have to exist. CDFs must exist.
Do the pdf and the pmf and the cdf contain the same information? PMFs are associated with discrete random variables, PDFs with continuous random variables. For any type of random of random variable, the CDF always exists (and is unique), defined as $$F_X(x) = P\{X
13,034
Do the pdf and the pmf and the cdf contain the same information?
The other answers point to the fact that CDFs are fundamental and must exist, whereas PDFs and PMFs are not and do not necessarily exist. This confused and intrigued me (being a non-statistician), as I did not know how to interpret a CDF (or how it might exist) when the sample space was not ordered; think, for example, of the circle $S^1$. It seems to me that the answer is that the fundamental function is the probability measure, which maps each (considered) subset of the sample space to a probability. Then, when they exist, the CDF, PDF and PMF arise from the probability measure.
Do the pdf and the pmf and the cdf contain the same information?
The other answers point to the fact that CDFs are fundamental and must exist, whereas PDFs and PMFs are not and do not necessarily exist. This confused and intrigued me (being a non-statistician), as
Do the pdf and the pmf and the cdf contain the same information? The other answers point to the fact that CDFs are fundamental and must exist, whereas PDFs and PMFs are not and do not necessarily exist. This confused and intrigued me (being a non-statistician), as I did not know how to interpret a CDF (or how it might exist) when the sample space was not ordered; think, for example, of the circle $S^1$. It seems to me that the answer is that the fundamental function is the probability measure, which maps each (considered) subset of the sample space to a probability. Then, when they exist, the CDF, PDF and PMF arise from the probability measure.
Do the pdf and the pmf and the cdf contain the same information? The other answers point to the fact that CDFs are fundamental and must exist, whereas PDFs and PMFs are not and do not necessarily exist. This confused and intrigued me (being a non-statistician), as
13,035
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics, by Freedman, Pisani, & Purves, originated from a popular and successful course taught at U.C. Berkeley. I have used it as an intro stats text for undergraduates, have borrowed some of its ideas when teaching graduate stats courses, and have given away many copies to colleagues and clients. There are many reasons for its popularity: Its narrative and its problems are driven by real case studies and actual data of obvious importance, rather than the made-up drivel found in so many texts. These are truly interesting and memorable, including the Salk polio vaccine trials, the 1936 Literary Digest poll debacle, the Berkeley graduate student discrimination lawsuit (hinging on Simpson's Paradox), Fisher's criticism of Mendel's pea results, and much more. It has extensive problems at three levels: at the end of each chapter subsection (of which there are hundreds), at the end of each chapter (over 30), and at the ends of major groups of chapters (about 4, I recall). These problems require minimal or no mathematics: they focus on potential misunderstandings that the authors, in their extensive experience, have found to arise among students. It focuses on statistical ideas and reasoning rather than mathematics. It uses (almost) no mathematical formulas. Quantitative relationships are usually expressed graphically and in words. (They are so clearly conveyed that when I first read this book, as a math graduate student entirely ignorant of statistics, I was able to reproduce all the underlying mathematical theory with no trouble.) It covers most of the traditional material, including the Binomial and Normal distributions, confidence intervals, z tests, t tests, chi squared tests, regression, and the minimum amount of probability and combinatorics needed to understand these. Some potential drawbacks would include: No treatment of Bayesian statistics. This will make this book outmoded within a decade. No treatment of ANOVA (psychology students might miss this the most). No discussion of computing. I believe the latter two are not critical: a good instructor can easily supply the ANOVA material and can teach as much or little computing as they might wish. Whether the omission of Bayesian statistics is important will depend on the instructor's tastes and aims. Finally, I should note that although the mathematical demands are as small as one could possibly imagine, my pre- and post-testing of students indicates that people who come to the book with a disposition and habit of thinking quantitatively still get much more out of it than those who do not. Most of my students performed badly on pretests of mathematical knowledge (90% got failing grades), but those who also performed badly on pretests of critical thinking (Shane Frederick's Cognitive Reflection Test) exhibited markedly less improvement during the semester than others did. The pre and post tests both included the full 40-item CAOS test of fundamental concepts any introductory college-level stats course ought to include. The students in this class have consistently exhibited twice as much improvement as that reported in the CAOS literature; the students with poor cognitive reflection scores improved only an average amount (or failed to complete the course). I haven't the data to assign causes to this extra improvement, but suspect the textbook deserves at least some of the credit.
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics, by Freedman, Pisani, & Purves, originated from a popular and successful course taught at U.C. Berkeley. I have used it as an intro stats text for undergraduates, have borrowed some of its
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics, by Freedman, Pisani, & Purves, originated from a popular and successful course taught at U.C. Berkeley. I have used it as an intro stats text for undergraduates, have borrowed some of its ideas when teaching graduate stats courses, and have given away many copies to colleagues and clients. There are many reasons for its popularity: Its narrative and its problems are driven by real case studies and actual data of obvious importance, rather than the made-up drivel found in so many texts. These are truly interesting and memorable, including the Salk polio vaccine trials, the 1936 Literary Digest poll debacle, the Berkeley graduate student discrimination lawsuit (hinging on Simpson's Paradox), Fisher's criticism of Mendel's pea results, and much more. It has extensive problems at three levels: at the end of each chapter subsection (of which there are hundreds), at the end of each chapter (over 30), and at the ends of major groups of chapters (about 4, I recall). These problems require minimal or no mathematics: they focus on potential misunderstandings that the authors, in their extensive experience, have found to arise among students. It focuses on statistical ideas and reasoning rather than mathematics. It uses (almost) no mathematical formulas. Quantitative relationships are usually expressed graphically and in words. (They are so clearly conveyed that when I first read this book, as a math graduate student entirely ignorant of statistics, I was able to reproduce all the underlying mathematical theory with no trouble.) It covers most of the traditional material, including the Binomial and Normal distributions, confidence intervals, z tests, t tests, chi squared tests, regression, and the minimum amount of probability and combinatorics needed to understand these. Some potential drawbacks would include: No treatment of Bayesian statistics. This will make this book outmoded within a decade. No treatment of ANOVA (psychology students might miss this the most). No discussion of computing. I believe the latter two are not critical: a good instructor can easily supply the ANOVA material and can teach as much or little computing as they might wish. Whether the omission of Bayesian statistics is important will depend on the instructor's tastes and aims. Finally, I should note that although the mathematical demands are as small as one could possibly imagine, my pre- and post-testing of students indicates that people who come to the book with a disposition and habit of thinking quantitatively still get much more out of it than those who do not. Most of my students performed badly on pretests of mathematical knowledge (90% got failing grades), but those who also performed badly on pretests of critical thinking (Shane Frederick's Cognitive Reflection Test) exhibited markedly less improvement during the semester than others did. The pre and post tests both included the full 40-item CAOS test of fundamental concepts any introductory college-level stats course ought to include. The students in this class have consistently exhibited twice as much improvement as that reported in the CAOS literature; the students with poor cognitive reflection scores improved only an average amount (or failed to complete the course). I haven't the data to assign causes to this extra improvement, but suspect the textbook deserves at least some of the credit.
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics, by Freedman, Pisani, & Purves, originated from a popular and successful course taught at U.C. Berkeley. I have used it as an intro stats text for undergraduates, have borrowed some of its
13,036
Any suggestions for a good undergraduate introductory textbook to statistics?
I read Freedman (almost the entire book) and OpenIntro Statistics (more than a third). Both of these books are quite good. I eventually found the book that came close to what I was looking for: Learning Statistics with R: A tutorial for psychology students and other beginners by Danielle Navarro. It is freely available online (legally) and you can also order a print version for about US $30 (see the book page for details). The main pros of this book are: R implementations embedded in text as topics are introduced. R has built-in functions for most of the methods explained in the book. Where R doesn't have a built-in, the author has written her own function for it and made it available on CRAN under her lsr library, so your learning is quite complete. I personally found this to be the biggest plus point of this book. The book is more comprehensive than Freedman and OpenIntro. Along with the basics, it covers topics like Shapiro-Wilk test, Wilcoxon test, Spearman correlation, trimmed means and a chapter on Bayesian statistics, to name a few. The motivation behind each topic is explained clearly. There is also a good amount of history behind the topics, so you get to appreciate how a method was arrived at. The book was written iteratively with feedback from readers and I believe the author is still improving upon the book. The only drawback is that the hard copy version is large and heavy!
Any suggestions for a good undergraduate introductory textbook to statistics?
I read Freedman (almost the entire book) and OpenIntro Statistics (more than a third). Both of these books are quite good. I eventually found the book that came close to what I was looking for: Learni
Any suggestions for a good undergraduate introductory textbook to statistics? I read Freedman (almost the entire book) and OpenIntro Statistics (more than a third). Both of these books are quite good. I eventually found the book that came close to what I was looking for: Learning Statistics with R: A tutorial for psychology students and other beginners by Danielle Navarro. It is freely available online (legally) and you can also order a print version for about US $30 (see the book page for details). The main pros of this book are: R implementations embedded in text as topics are introduced. R has built-in functions for most of the methods explained in the book. Where R doesn't have a built-in, the author has written her own function for it and made it available on CRAN under her lsr library, so your learning is quite complete. I personally found this to be the biggest plus point of this book. The book is more comprehensive than Freedman and OpenIntro. Along with the basics, it covers topics like Shapiro-Wilk test, Wilcoxon test, Spearman correlation, trimmed means and a chapter on Bayesian statistics, to name a few. The motivation behind each topic is explained clearly. There is also a good amount of history behind the topics, so you get to appreciate how a method was arrived at. The book was written iteratively with feedback from readers and I believe the author is still improving upon the book. The only drawback is that the hard copy version is large and heavy!
Any suggestions for a good undergraduate introductory textbook to statistics? I read Freedman (almost the entire book) and OpenIntro Statistics (more than a third). Both of these books are quite good. I eventually found the book that came close to what I was looking for: Learni
13,037
Any suggestions for a good undergraduate introductory textbook to statistics?
Thom Baguley, an outgoing editor of The British Journal of Mathematical and Statistical Psychology, published Serious Stats book that you could find useful. It relies on R rather than SPSS, though. I am suspicious of the books that are in their 7th edition. In my teaching experience, it means that the sections and problems were reshuffled so that the students would have to buy the latest edition to generate the cash flow for the publisher and royalties for the authors keep up with the course. Few serious, research level monographs have undergone a second edition by their authors, and any higher number is obviously an outlier. (Kendall's Library of Statistics is a notable exception, but I cannot really think of any other book that I know that would be in its third edition.) In my very strong opinion, Excel is a good tool for statistical analysis only when used by a Ph.D. statistician. Teaching undergraduate statistics with it will likely have disastrous consequences, and teaches little statistics as compared to using a modern package like R or Stata. Just try to produce a standardized residual vs. leverage regression plot in Excel, and compare it to one-liners in these packages. Stat majors would need to know the theory, so they would need to build these plots from scratch, but still using a statistical package rather than copy/paste the formulae around in Excel. Non-major undergrads need to get the feel for data analysis, and Excel obscures it, at best.
Any suggestions for a good undergraduate introductory textbook to statistics?
Thom Baguley, an outgoing editor of The British Journal of Mathematical and Statistical Psychology, published Serious Stats book that you could find useful. It relies on R rather than SPSS, though. I
Any suggestions for a good undergraduate introductory textbook to statistics? Thom Baguley, an outgoing editor of The British Journal of Mathematical and Statistical Psychology, published Serious Stats book that you could find useful. It relies on R rather than SPSS, though. I am suspicious of the books that are in their 7th edition. In my teaching experience, it means that the sections and problems were reshuffled so that the students would have to buy the latest edition to generate the cash flow for the publisher and royalties for the authors keep up with the course. Few serious, research level monographs have undergone a second edition by their authors, and any higher number is obviously an outlier. (Kendall's Library of Statistics is a notable exception, but I cannot really think of any other book that I know that would be in its third edition.) In my very strong opinion, Excel is a good tool for statistical analysis only when used by a Ph.D. statistician. Teaching undergraduate statistics with it will likely have disastrous consequences, and teaches little statistics as compared to using a modern package like R or Stata. Just try to produce a standardized residual vs. leverage regression plot in Excel, and compare it to one-liners in these packages. Stat majors would need to know the theory, so they would need to build these plots from scratch, but still using a statistical package rather than copy/paste the formulae around in Excel. Non-major undergrads need to get the feel for data analysis, and Excel obscures it, at best.
Any suggestions for a good undergraduate introductory textbook to statistics? Thom Baguley, an outgoing editor of The British Journal of Mathematical and Statistical Psychology, published Serious Stats book that you could find useful. It relies on R rather than SPSS, though. I
13,038
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics Unplugged is a great book for introductory statistics. The author first introduces the logic of the statistical test and later gives the mathematical formula. This approach helps in digesting the new concepts. There are several examples throughout the book which are presented in the form of a problem required to be solved rather than a hypothetical statement and mathematical steps.
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics Unplugged is a great book for introductory statistics. The author first introduces the logic of the statistical test and later gives the mathematical formula. This approach helps in digesti
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics Unplugged is a great book for introductory statistics. The author first introduces the logic of the statistical test and later gives the mathematical formula. This approach helps in digesting the new concepts. There are several examples throughout the book which are presented in the form of a problem required to be solved rather than a hypothetical statement and mathematical steps.
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics Unplugged is a great book for introductory statistics. The author first introduces the logic of the statistical test and later gives the mathematical formula. This approach helps in digesti
13,039
Any suggestions for a good undergraduate introductory textbook to statistics?
How about The Statistical Sleuth by Ramsey and Schafer? I think this book gets at some important points without either a) Too much math or b) dumbing things down. I would suggest that an intro stats course for psychology and other social science types should emphasize how not to go wrong too much. A survey of methods would also be a good thing for undergrads to get.
Any suggestions for a good undergraduate introductory textbook to statistics?
How about The Statistical Sleuth by Ramsey and Schafer? I think this book gets at some important points without either a) Too much math or b) dumbing things down. I would suggest that an intro stats c
Any suggestions for a good undergraduate introductory textbook to statistics? How about The Statistical Sleuth by Ramsey and Schafer? I think this book gets at some important points without either a) Too much math or b) dumbing things down. I would suggest that an intro stats course for psychology and other social science types should emphasize how not to go wrong too much. A survey of methods would also be a good thing for undergrads to get.
Any suggestions for a good undergraduate introductory textbook to statistics? How about The Statistical Sleuth by Ramsey and Schafer? I think this book gets at some important points without either a) Too much math or b) dumbing things down. I would suggest that an intro stats c
13,040
Any suggestions for a good undergraduate introductory textbook to statistics?
Check out the introductory statistics book, Making Sense of Data through Statistics: An Introduction (2014) by Dorit Nevo. It is written in an extremely accessible manner and is meant for undergraduate or graduate students in business and in the social sciences. The textbook makes use of examples meaningful to today’s students and is accompanied with Excel worksheets providing hands-on experience that reinforces the statistical concepts and techniques covered. Instructors are provided with supplementary teaching materials, including PPT lecture slides for each chapter, a Solutions Manual for all Unit Exercises and End-of-Chapter Practice sets, and a Test Bank. The book is sold in digital format only (.pdf), allowing for the very reasonable price of $19.95. Educators may register for free access to the book and teaching materials by signing up at the Legerity Digital Press Educator Preview portal.
Any suggestions for a good undergraduate introductory textbook to statistics?
Check out the introductory statistics book, Making Sense of Data through Statistics: An Introduction (2014) by Dorit Nevo. It is written in an extremely accessible manner and is meant for undergradua
Any suggestions for a good undergraduate introductory textbook to statistics? Check out the introductory statistics book, Making Sense of Data through Statistics: An Introduction (2014) by Dorit Nevo. It is written in an extremely accessible manner and is meant for undergraduate or graduate students in business and in the social sciences. The textbook makes use of examples meaningful to today’s students and is accompanied with Excel worksheets providing hands-on experience that reinforces the statistical concepts and techniques covered. Instructors are provided with supplementary teaching materials, including PPT lecture slides for each chapter, a Solutions Manual for all Unit Exercises and End-of-Chapter Practice sets, and a Test Bank. The book is sold in digital format only (.pdf), allowing for the very reasonable price of $19.95. Educators may register for free access to the book and teaching materials by signing up at the Legerity Digital Press Educator Preview portal.
Any suggestions for a good undergraduate introductory textbook to statistics? Check out the introductory statistics book, Making Sense of Data through Statistics: An Introduction (2014) by Dorit Nevo. It is written in an extremely accessible manner and is meant for undergradua
13,041
Any suggestions for a good undergraduate introductory textbook to statistics?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Here is a list of books. Puzzles/riddles are a great way to instil an interest in what mathematics/statistics can do. Real life examples help too.
Any suggestions for a good undergraduate introductory textbook to statistics?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Any suggestions for a good undergraduate introductory textbook to statistics? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Here is a list of books. Puzzles/riddles are a great way to instil an interest in what mathematics/statistics can do. Real life examples help too.
Any suggestions for a good undergraduate introductory textbook to statistics? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
13,042
Any suggestions for a good undergraduate introductory textbook to statistics?
I have been a TA, observer, or student in a lot of courses involving quantitative methods for psychology, with SPSS as the main program. In all cases it has seemed to me that students have gravitated towards Field (2013), irrespective of whether the course coordinator has mentioned this book or not. In numerous cases students have ignored a recommended textbook and read Field's textbook instead. I'm not properly competent to assess the rigour of the explanations in the book, and nor am I aware of any research on learning outcomes. However, I can say that this book is comprehensive, cheap (where I'm from anyway), and popular with students. The author's writing style relies a great deal on personal anecdotes, which will grate with some readers. However, I've found that at least as many students enjoy it. I seemed to run into a lot of typos and other issues in the early editions, but by the fourth edition most of these seem to be weeded out. So, Field (2013) is my recommendation, since: I've seen psychology students engage with it and enjoy reading it. Even if you recommend another book, it's quite likely that some students will use Field (2013) anyway. This can then create administration issues within your course. The book is popular and the author is still relatively young, so it's likely that there will be further editions and improvements. If you later decide that you want to use R instead, you can transition pretty seamlessly to Field, Miles, and Field (2012), which uses most of the same examples. @jeremy-miles is a frequent contributor to this site. Field, A. (2013). Discovering statistics using IBM SPSS statistics. Sage. Field, A., Miles, J., & Field, Z (2012). Discovering Statistics Using R. Sage.
Any suggestions for a good undergraduate introductory textbook to statistics?
I have been a TA, observer, or student in a lot of courses involving quantitative methods for psychology, with SPSS as the main program. In all cases it has seemed to me that students have gravitated
Any suggestions for a good undergraduate introductory textbook to statistics? I have been a TA, observer, or student in a lot of courses involving quantitative methods for psychology, with SPSS as the main program. In all cases it has seemed to me that students have gravitated towards Field (2013), irrespective of whether the course coordinator has mentioned this book or not. In numerous cases students have ignored a recommended textbook and read Field's textbook instead. I'm not properly competent to assess the rigour of the explanations in the book, and nor am I aware of any research on learning outcomes. However, I can say that this book is comprehensive, cheap (where I'm from anyway), and popular with students. The author's writing style relies a great deal on personal anecdotes, which will grate with some readers. However, I've found that at least as many students enjoy it. I seemed to run into a lot of typos and other issues in the early editions, but by the fourth edition most of these seem to be weeded out. So, Field (2013) is my recommendation, since: I've seen psychology students engage with it and enjoy reading it. Even if you recommend another book, it's quite likely that some students will use Field (2013) anyway. This can then create administration issues within your course. The book is popular and the author is still relatively young, so it's likely that there will be further editions and improvements. If you later decide that you want to use R instead, you can transition pretty seamlessly to Field, Miles, and Field (2012), which uses most of the same examples. @jeremy-miles is a frequent contributor to this site. Field, A. (2013). Discovering statistics using IBM SPSS statistics. Sage. Field, A., Miles, J., & Field, Z (2012). Discovering Statistics Using R. Sage.
Any suggestions for a good undergraduate introductory textbook to statistics? I have been a TA, observer, or student in a lot of courses involving quantitative methods for psychology, with SPSS as the main program. In all cases it has seemed to me that students have gravitated
13,043
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics for College Students and Researchers: Grasping the Concepts, Paperback 2010, ISBN-13 : 978-1453604533 is perhaps the easiest and most comprehensive stat book for college students. "grasping the concepts and the logic of Statistics. Formulas do not lead to understanding, they actually prevent it. This book takes you through elementary, intermediate and advanced Statistics with only five simple formulas! Descriptive and inferential Statistics. t-test, one-way analysis of variance (ANOVA), two-way ANOVA, repeated measures, factorial designs unlimited, complex split-plot designs.". Unbelievable? Yes... I got the book, the description at amazon is correct. The author is a psychologist/medical anatomist, so examples come from these areas. Apparently these are his lectures. Concepts are developed through funny stories. Yes, five simple formulas all the way through ANOVA. ANOVA summary tables become redundant, although all example cases use them.
Any suggestions for a good undergraduate introductory textbook to statistics?
Statistics for College Students and Researchers: Grasping the Concepts, Paperback 2010, ISBN-13 : 978-1453604533 is perhaps the easiest and most comprehensive stat book for college students. "graspin
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics for College Students and Researchers: Grasping the Concepts, Paperback 2010, ISBN-13 : 978-1453604533 is perhaps the easiest and most comprehensive stat book for college students. "grasping the concepts and the logic of Statistics. Formulas do not lead to understanding, they actually prevent it. This book takes you through elementary, intermediate and advanced Statistics with only five simple formulas! Descriptive and inferential Statistics. t-test, one-way analysis of variance (ANOVA), two-way ANOVA, repeated measures, factorial designs unlimited, complex split-plot designs.". Unbelievable? Yes... I got the book, the description at amazon is correct. The author is a psychologist/medical anatomist, so examples come from these areas. Apparently these are his lectures. Concepts are developed through funny stories. Yes, five simple formulas all the way through ANOVA. ANOVA summary tables become redundant, although all example cases use them.
Any suggestions for a good undergraduate introductory textbook to statistics? Statistics for College Students and Researchers: Grasping the Concepts, Paperback 2010, ISBN-13 : 978-1453604533 is perhaps the easiest and most comprehensive stat book for college students. "graspin
13,044
Any suggestions for a good undergraduate introductory textbook to statistics?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. http://onlinestatbook.com/index.html is a very nice source with simulations and videos
Any suggestions for a good undergraduate introductory textbook to statistics?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Any suggestions for a good undergraduate introductory textbook to statistics? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. http://onlinestatbook.com/index.html is a very nice source with simulations and videos
Any suggestions for a good undergraduate introductory textbook to statistics? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
13,045
Mean and Median properties
This is two questions: one about how the mean and median minimize loss functions and another about the sensitivities of these estimates to the data. The two questions are connected, as we will see. Minimizing Loss A summary (or estimator) of the center of a batch of numbers can be created by letting the summary value change and imagining that each number in the batch exerts a restoring force on that value. When the force never pushes the value away from a number, then arguably any point at which the forces balance is a "center" of the batch. Quadratic ($L_2$) Loss For instance, if we were to attach a classical spring (following Hooke's Law) between the summary and each number, the force would be proportional to the distance to each spring. The springs would pull the summary this way and that, eventually settling to a unique stable location of minimal energy. I would like to draw notice to a little sleight-of-hand that just occurred: the energy is proportional to the sum of squared distances. Newtonian mechanics teaches us that force is the rate of change of energy. Achieving an equilibrium--minimizing the energy--results in balancing the forces. The net rate of change in the energy is zero. Let's call this the "$L_2$ summary," or "squared loss summary." Absolute ($L_1$) Loss Another summary can be created by supposing the sizes of the restoring forces are constant, regardless of the distances between the value and the data. The forces themselves are not constant, however, because they must always pull the value towards each data point. Thus, when the value is less than the data point the force is directed positively, but when the value is greater than the data point the force is directed negatively. Now the energy is proportional to the distances between the value and the data. There typically will be an entire region in which the energy is constant and the net force is zero. Any value in this region we might call the "$L_1$ summary" or "absolute loss summary." These physical analogies provide useful intuition about the two summaries. For instance, what happens to the summary if we move one of the data points? In the $L_2$ case with springs attached, moving one data point either stretches or relaxes its spring. The result is a change in force on the summary, so it must change in response. But in the $L_1$ case, most of the time a change in a data point does nothing to the summary, because the force is locally constant. The only way the force can change is for the data point to move across the summary. (In fact, it should be evident that the net force on a value is given by the number of points greater than it--which pull it upwards--minus the number of points less than it--which pull it downwards. Thus, the $L_1$ summary must occur at any location where the number of data values exceeding it exactly equals the number of data values less than it.) Depicting Losses Since both forces and energies add up, in either case we can decompose the net energy into individual contributions from the data points. By graphing the energy or force as a function of the summary value, this provides a detailed picture of what is happening. The summary will be a location at which the energy (or "loss" in statistical parlance) is smallest. Equivalently, it will be a location at which forces balance: the center of the data occurs where the net change in loss is zero. This figure shows energies and forces for a small dataset of six values (marked by faint vertical lines in each plot). The dashed black curves are the totals of the colored curves showing the contributions from the individual values. The x-axis indicates possible values of the summary. The arithmetic mean is a point where squared loss is minimized: it will be located at the vertex (bottom) of the black parabola in the upper left plot. It is always unique. The median is a point where absolute loss is minimized. As noted above, it must occur in the middle of the data. It is not necessarily unique. It will be located at the bottom of the broken black curve in the upper right. (The bottom actually consists of a short flat section between $-0.23$ and $-0.17$; any value in this interval is a median.) Analyzing Sensitivity Earlier I described what can happen to the summary when a data point is varied. It is instructive to plot how the summary changes in response to changing any single data point. (These plots are essentially the empirical influence functions. They differ from the usual definition in that they show the actual values of the estimates rather than how much those values are changed.) The value of the summary is labeled by "Estimate" on the y-axes to remind us that this summary is estimating where the middle of the dataset lies. The new (changed) values of each data point are shown on their x-axes. This figure presents the results of varying each of the data values in the batch $-1.02, -0.82, -0.23, -0.17, -0.08, 0.77$ (the same one analyzed in the first figure). There is one plot for each data value, which is highlighted on its plot with a long black tick along the bottom axis. (The remaining data values are shown with short gray ticks.) The blue curve traces the $L_2$ summary--the arithmetic mean--and the red curve traces the $L_1$ summary--the median. (Since often the median is a range of values, the convention of plotting the middle of that range is followed here.) Notice: The sensitivity of the mean is unbounded: those blue lines extend infinitely far up and down. The sensitivity of the median is bounded: there are upper and lower limits to the red curves. Where the median does change, though, it changes much more rapidly than the mean. The slope of each blue line is $1/6$ (generally it is $1/n$ for a dataset with $n$ values), whereas the slopes of the tilted parts of the red lines are all $1/2$. The mean is sensitive to every data point and this sensitivity has no bounds (as the nonzero slopes of all the colored lines in the bottom left plot of the first figure indicate). Although the median is sensitive to every data point, the sensitivity is bounded (which is why the colored curves in the bottom right plot of the first figure are located within a narrow vertical range around zero). These, of course, are merely visual reiterations of the basic force (loss) law: quadratic for the mean, linear for the median. The interval over which the median can be made to change can vary among the data points. It is always bounded by two of the near-middle values among the data which are not varying. (These boundaries are marked by faint vertical dashed lines.) Because the rate of change of the median is always $1/2$, the amount by which it might vary therefore is determined by the length of this gap between near-middle values of the dataset. Although only the first point is commonly noted, all the points are important. In particular, It is definitely false that the "median does not depend on every value." This figure provides a counterexample. Nevertheless, the median does not depend "materially" on every value in the sense that although changing individual values can change the median, the amount of change is limited by the gaps among near-middle values in the dataset. In particular, the amount of change is bounded. We say that the median is a "resistant" summary. Although the mean is not resistant, and will change whenever any data value is changed, the rate of change is relatively small. The larger the dataset, the smaller the rate of change. Equivalently, in order to produce a material change in the mean of a large dataset, at least one value must undergo a relatively large variation. This suggests the non-resistance of the mean is of concern only for (a) small datasets or (b) datasets where one or more data might have values extremely far from the middle of the batch. These remarks--which I hope the figures make evident--reveal a deep connection between the loss function and the sensitivity (or resistance) of the estimator. For more about this, begin with one of the Wikipedia articles on M-estimators and then pursue those ideas as far as you like. Code This R code produced the figures and can readily be modified to study any other dataset in the same way: simply replace the randomly-created vector y with any vector of numbers. # # Create a small dataset. # set.seed(17) y <- sort(rnorm(6)) # Some data # # Study how a statistic varies when the first element of a dataset # is modified. # statistic.vary <- function(t, x, statistic) { sapply(t, function(e) statistic(c(e, x[-1]))) } # # Prepare for plotting. # darken <- function(c, x=0.8) { apply(col2rgb(c)/255 * x, 2, function(s) rgb(s[1], s[2], s[3])) } colors <- darken(c("Blue", "Red")) statistics <- c(mean, median); names(statistics) <- c("mean", "median") x.limits <- range(y) + c(-1, 1) y.limits <- range(sapply(statistics, function(f) statistic.vary(x.limits + c(-1,1), c(0,y), f))) # # Make the plots. # par(mfrow=c(2,3)) for (i in 1:length(y)) { # # Create a standard, consistent plot region. # plot(x.limits, y.limits, type="n", xlab=paste("Value of y[", i, "]", sep=""), ylab="Estimate", main=paste("Sensitivity to y[", i, "]", sep="")) #legend("topleft", legend=names(statistics), col=colors, lwd=1) # # Mark the limits of the possible medians. # n <- length(y)/2 bars <- sort(y[-1])[ceiling(n-1):floor(n+1)] abline(v=range(bars), lty=2, col="Gray") rug(y, col="Gray", ticksize=0.05); # # Show which value is being varied. # rug(y[1], col="Black", ticksize=0.075, lwd=2) # # Plot the statistics as the value is varied between x.limits. # invisible(mapply(function(f,c) curve(statistic.vary(x, y, f), col=c, lwd=2, add=TRUE, n=501), statistics, colors)) y <- c(y[-1], y[1]) # Move the next data value to the front } #------------------------------------------------------------------------------# # # Study loss functions. # loss <- function(x, y, f) sapply(x, function(t) sum(f(y-t))) square <- function(t) t^2 square.d <- function(t) 2*t abs.d <- sign losses <- c(square, abs, square.d, abs.d) names(losses) <- c("Squared Loss", "Absolute Loss", "Change in Squared Loss", "Change in Absolute Loss") loss.types <- c(rep("Loss (energy)", 2), rep("Change in loss (force)", 2)) # # Prepare for plotting. # colors <- darken(rainbow(length(y))) x.limits <- range(y) + c(-1, 1)/2 # # Make the plots. # par(mfrow=c(2,2)) for (j in 1:length(losses)) { f <- losses[[j]] y.range <- range(c(0, 1.1*loss(y, y, f))) # # Plot the loss (or its rate of change). # curve(loss(x, y, f), from=min(x.limits), to=max(x.limits), n=1001, lty=3, ylim=y.range, xlab="Value", ylab=loss.types[j], main=names(losses)[j]) # # Draw the x-axis if needed. # if (sign(prod(y.range))==-1) abline(h=0, col="Gray") # # Faintly mark the data values. # abline(v=y, col="#00000010") # # Plot contributions to the loss (or its rate of change). # for (i in 1:length(y)) { curve(loss(x, y[i], f), add=TRUE, lty=1, col=colors[i], n=1001) } rug(y, side=3) }
Mean and Median properties
This is two questions: one about how the mean and median minimize loss functions and another about the sensitivities of these estimates to the data. The two questions are connected, as we will see. M
Mean and Median properties This is two questions: one about how the mean and median minimize loss functions and another about the sensitivities of these estimates to the data. The two questions are connected, as we will see. Minimizing Loss A summary (or estimator) of the center of a batch of numbers can be created by letting the summary value change and imagining that each number in the batch exerts a restoring force on that value. When the force never pushes the value away from a number, then arguably any point at which the forces balance is a "center" of the batch. Quadratic ($L_2$) Loss For instance, if we were to attach a classical spring (following Hooke's Law) between the summary and each number, the force would be proportional to the distance to each spring. The springs would pull the summary this way and that, eventually settling to a unique stable location of minimal energy. I would like to draw notice to a little sleight-of-hand that just occurred: the energy is proportional to the sum of squared distances. Newtonian mechanics teaches us that force is the rate of change of energy. Achieving an equilibrium--minimizing the energy--results in balancing the forces. The net rate of change in the energy is zero. Let's call this the "$L_2$ summary," or "squared loss summary." Absolute ($L_1$) Loss Another summary can be created by supposing the sizes of the restoring forces are constant, regardless of the distances between the value and the data. The forces themselves are not constant, however, because they must always pull the value towards each data point. Thus, when the value is less than the data point the force is directed positively, but when the value is greater than the data point the force is directed negatively. Now the energy is proportional to the distances between the value and the data. There typically will be an entire region in which the energy is constant and the net force is zero. Any value in this region we might call the "$L_1$ summary" or "absolute loss summary." These physical analogies provide useful intuition about the two summaries. For instance, what happens to the summary if we move one of the data points? In the $L_2$ case with springs attached, moving one data point either stretches or relaxes its spring. The result is a change in force on the summary, so it must change in response. But in the $L_1$ case, most of the time a change in a data point does nothing to the summary, because the force is locally constant. The only way the force can change is for the data point to move across the summary. (In fact, it should be evident that the net force on a value is given by the number of points greater than it--which pull it upwards--minus the number of points less than it--which pull it downwards. Thus, the $L_1$ summary must occur at any location where the number of data values exceeding it exactly equals the number of data values less than it.) Depicting Losses Since both forces and energies add up, in either case we can decompose the net energy into individual contributions from the data points. By graphing the energy or force as a function of the summary value, this provides a detailed picture of what is happening. The summary will be a location at which the energy (or "loss" in statistical parlance) is smallest. Equivalently, it will be a location at which forces balance: the center of the data occurs where the net change in loss is zero. This figure shows energies and forces for a small dataset of six values (marked by faint vertical lines in each plot). The dashed black curves are the totals of the colored curves showing the contributions from the individual values. The x-axis indicates possible values of the summary. The arithmetic mean is a point where squared loss is minimized: it will be located at the vertex (bottom) of the black parabola in the upper left plot. It is always unique. The median is a point where absolute loss is minimized. As noted above, it must occur in the middle of the data. It is not necessarily unique. It will be located at the bottom of the broken black curve in the upper right. (The bottom actually consists of a short flat section between $-0.23$ and $-0.17$; any value in this interval is a median.) Analyzing Sensitivity Earlier I described what can happen to the summary when a data point is varied. It is instructive to plot how the summary changes in response to changing any single data point. (These plots are essentially the empirical influence functions. They differ from the usual definition in that they show the actual values of the estimates rather than how much those values are changed.) The value of the summary is labeled by "Estimate" on the y-axes to remind us that this summary is estimating where the middle of the dataset lies. The new (changed) values of each data point are shown on their x-axes. This figure presents the results of varying each of the data values in the batch $-1.02, -0.82, -0.23, -0.17, -0.08, 0.77$ (the same one analyzed in the first figure). There is one plot for each data value, which is highlighted on its plot with a long black tick along the bottom axis. (The remaining data values are shown with short gray ticks.) The blue curve traces the $L_2$ summary--the arithmetic mean--and the red curve traces the $L_1$ summary--the median. (Since often the median is a range of values, the convention of plotting the middle of that range is followed here.) Notice: The sensitivity of the mean is unbounded: those blue lines extend infinitely far up and down. The sensitivity of the median is bounded: there are upper and lower limits to the red curves. Where the median does change, though, it changes much more rapidly than the mean. The slope of each blue line is $1/6$ (generally it is $1/n$ for a dataset with $n$ values), whereas the slopes of the tilted parts of the red lines are all $1/2$. The mean is sensitive to every data point and this sensitivity has no bounds (as the nonzero slopes of all the colored lines in the bottom left plot of the first figure indicate). Although the median is sensitive to every data point, the sensitivity is bounded (which is why the colored curves in the bottom right plot of the first figure are located within a narrow vertical range around zero). These, of course, are merely visual reiterations of the basic force (loss) law: quadratic for the mean, linear for the median. The interval over which the median can be made to change can vary among the data points. It is always bounded by two of the near-middle values among the data which are not varying. (These boundaries are marked by faint vertical dashed lines.) Because the rate of change of the median is always $1/2$, the amount by which it might vary therefore is determined by the length of this gap between near-middle values of the dataset. Although only the first point is commonly noted, all the points are important. In particular, It is definitely false that the "median does not depend on every value." This figure provides a counterexample. Nevertheless, the median does not depend "materially" on every value in the sense that although changing individual values can change the median, the amount of change is limited by the gaps among near-middle values in the dataset. In particular, the amount of change is bounded. We say that the median is a "resistant" summary. Although the mean is not resistant, and will change whenever any data value is changed, the rate of change is relatively small. The larger the dataset, the smaller the rate of change. Equivalently, in order to produce a material change in the mean of a large dataset, at least one value must undergo a relatively large variation. This suggests the non-resistance of the mean is of concern only for (a) small datasets or (b) datasets where one or more data might have values extremely far from the middle of the batch. These remarks--which I hope the figures make evident--reveal a deep connection between the loss function and the sensitivity (or resistance) of the estimator. For more about this, begin with one of the Wikipedia articles on M-estimators and then pursue those ideas as far as you like. Code This R code produced the figures and can readily be modified to study any other dataset in the same way: simply replace the randomly-created vector y with any vector of numbers. # # Create a small dataset. # set.seed(17) y <- sort(rnorm(6)) # Some data # # Study how a statistic varies when the first element of a dataset # is modified. # statistic.vary <- function(t, x, statistic) { sapply(t, function(e) statistic(c(e, x[-1]))) } # # Prepare for plotting. # darken <- function(c, x=0.8) { apply(col2rgb(c)/255 * x, 2, function(s) rgb(s[1], s[2], s[3])) } colors <- darken(c("Blue", "Red")) statistics <- c(mean, median); names(statistics) <- c("mean", "median") x.limits <- range(y) + c(-1, 1) y.limits <- range(sapply(statistics, function(f) statistic.vary(x.limits + c(-1,1), c(0,y), f))) # # Make the plots. # par(mfrow=c(2,3)) for (i in 1:length(y)) { # # Create a standard, consistent plot region. # plot(x.limits, y.limits, type="n", xlab=paste("Value of y[", i, "]", sep=""), ylab="Estimate", main=paste("Sensitivity to y[", i, "]", sep="")) #legend("topleft", legend=names(statistics), col=colors, lwd=1) # # Mark the limits of the possible medians. # n <- length(y)/2 bars <- sort(y[-1])[ceiling(n-1):floor(n+1)] abline(v=range(bars), lty=2, col="Gray") rug(y, col="Gray", ticksize=0.05); # # Show which value is being varied. # rug(y[1], col="Black", ticksize=0.075, lwd=2) # # Plot the statistics as the value is varied between x.limits. # invisible(mapply(function(f,c) curve(statistic.vary(x, y, f), col=c, lwd=2, add=TRUE, n=501), statistics, colors)) y <- c(y[-1], y[1]) # Move the next data value to the front } #------------------------------------------------------------------------------# # # Study loss functions. # loss <- function(x, y, f) sapply(x, function(t) sum(f(y-t))) square <- function(t) t^2 square.d <- function(t) 2*t abs.d <- sign losses <- c(square, abs, square.d, abs.d) names(losses) <- c("Squared Loss", "Absolute Loss", "Change in Squared Loss", "Change in Absolute Loss") loss.types <- c(rep("Loss (energy)", 2), rep("Change in loss (force)", 2)) # # Prepare for plotting. # colors <- darken(rainbow(length(y))) x.limits <- range(y) + c(-1, 1)/2 # # Make the plots. # par(mfrow=c(2,2)) for (j in 1:length(losses)) { f <- losses[[j]] y.range <- range(c(0, 1.1*loss(y, y, f))) # # Plot the loss (or its rate of change). # curve(loss(x, y, f), from=min(x.limits), to=max(x.limits), n=1001, lty=3, ylim=y.range, xlab="Value", ylab=loss.types[j], main=names(losses)[j]) # # Draw the x-axis if needed. # if (sign(prod(y.range))==-1) abline(h=0, col="Gray") # # Faintly mark the data values. # abline(v=y, col="#00000010") # # Plot contributions to the loss (or its rate of change). # for (i in 1:length(y)) { curve(loss(x, y[i], f), add=TRUE, lty=1, col=colors[i], n=1001) } rug(y, side=3) }
Mean and Median properties This is two questions: one about how the mean and median minimize loss functions and another about the sensitivities of these estimates to the data. The two questions are connected, as we will see. M
13,046
Mean and Median properties
For the computation of the median, let $x_1,x_2,\ldots,x_n$ be the data. Assume, for simplicity, that $n$ is even, and the points are distinct! Let $y$ be some number. Let $f(y)$ be the 'sum-of-absolute deviations' of $y$ to the points $x_i$. This means that $f(y) = |x_1 - y| + |x_2 - y| + \ldots + |x_n - y|$. Your goal is to find the $y$ that minimizes $f(y)$. Let $l$ be the number of the $x_i$ that are less than or exactly equal to $y$ at a given point in time, and let $r = n - l$ be the number that are strictly greater than $y$. Pretend you are 'moving $y$ to the right', that is, increase $y$ slightly. What happens to $f(y)$? Suppose you add an amount of $\Delta y$ to $y$. For those $x_i$ which are less than or equal to $y$, we have $|x_i - y|$ increases by $\Delta y$. And for those greater than $y$, we have $|x_i - y|$ decreases by $\Delta y$. (This assumes $\Delta y$ is so small that $y$ does not cross any of the points). Thus the change in $f(y)$ is $l\Delta y - r \Delta y = (l-r)\Delta y$. Note that this change in $f(y)$ does not depend on the values of the $x_i$ but only on the number to the left and right of $y$. By definition, $y$ is a median value when moving it to the left or right does not increase or decrease $f(y)$. This would mean that $l-r = 0$, and thus the number of $x_i$ to the left of $y$ is equal to the number to the right of $y$. And thus the median does not depend on the values of $x_i$, just their locations. edit For the mean: the function $f(y)$ becomes $f(y) = (x_1 - y)^2 + \ldots + (x_n - y)^2$. Clearly the change in $f(y)$ for a small change in $y$ now depends on the magnitudes of the $x_i$, not just the number to the left and right of $y$. Note that this business about the 'small change' is just covert talk for the derivative of $f(y)$...
Mean and Median properties
For the computation of the median, let $x_1,x_2,\ldots,x_n$ be the data. Assume, for simplicity, that $n$ is even, and the points are distinct! Let $y$ be some number. Let $f(y)$ be the 'sum-of-absolu
Mean and Median properties For the computation of the median, let $x_1,x_2,\ldots,x_n$ be the data. Assume, for simplicity, that $n$ is even, and the points are distinct! Let $y$ be some number. Let $f(y)$ be the 'sum-of-absolute deviations' of $y$ to the points $x_i$. This means that $f(y) = |x_1 - y| + |x_2 - y| + \ldots + |x_n - y|$. Your goal is to find the $y$ that minimizes $f(y)$. Let $l$ be the number of the $x_i$ that are less than or exactly equal to $y$ at a given point in time, and let $r = n - l$ be the number that are strictly greater than $y$. Pretend you are 'moving $y$ to the right', that is, increase $y$ slightly. What happens to $f(y)$? Suppose you add an amount of $\Delta y$ to $y$. For those $x_i$ which are less than or equal to $y$, we have $|x_i - y|$ increases by $\Delta y$. And for those greater than $y$, we have $|x_i - y|$ decreases by $\Delta y$. (This assumes $\Delta y$ is so small that $y$ does not cross any of the points). Thus the change in $f(y)$ is $l\Delta y - r \Delta y = (l-r)\Delta y$. Note that this change in $f(y)$ does not depend on the values of the $x_i$ but only on the number to the left and right of $y$. By definition, $y$ is a median value when moving it to the left or right does not increase or decrease $f(y)$. This would mean that $l-r = 0$, and thus the number of $x_i$ to the left of $y$ is equal to the number to the right of $y$. And thus the median does not depend on the values of $x_i$, just their locations. edit For the mean: the function $f(y)$ becomes $f(y) = (x_1 - y)^2 + \ldots + (x_n - y)^2$. Clearly the change in $f(y)$ for a small change in $y$ now depends on the magnitudes of the $x_i$, not just the number to the left and right of $y$. Note that this business about the 'small change' is just covert talk for the derivative of $f(y)$...
Mean and Median properties For the computation of the median, let $x_1,x_2,\ldots,x_n$ be the data. Assume, for simplicity, that $n$ is even, and the points are distinct! Let $y$ be some number. Let $f(y)$ be the 'sum-of-absolu
13,047
Mean and Median properties
Roughly speaking, the median is the "middle value". Now, if you change the highest value (which is supposed to be positive here) from $x_{(n)}$ to $2 * x_{(n)}$, say, it does not change the median. But it does change the arithmetic mean. This shows, in simple terms, that the median does not depend on every value while the mean does. Actually, the median only depends on the ranks. The mathematical logic behind this simply arises from the mathematical definitions of the median and the mean. Now, it can be shown that, for any $ a \in \mathbb{R}$ $\sum_{i=1}^{n} |x_{i} - median| \leq \sum_{i=1}^{n} |x_{i} - a|$ and $\sum_{i=1}^{n} (x_{i} - mean)^{2} \leq \sum_{i=1}^{n} (x_{i} - a)^{2}$
Mean and Median properties
Roughly speaking, the median is the "middle value". Now, if you change the highest value (which is supposed to be positive here) from $x_{(n)}$ to $2 * x_{(n)}$, say, it does not change the median. B
Mean and Median properties Roughly speaking, the median is the "middle value". Now, if you change the highest value (which is supposed to be positive here) from $x_{(n)}$ to $2 * x_{(n)}$, say, it does not change the median. But it does change the arithmetic mean. This shows, in simple terms, that the median does not depend on every value while the mean does. Actually, the median only depends on the ranks. The mathematical logic behind this simply arises from the mathematical definitions of the median and the mean. Now, it can be shown that, for any $ a \in \mathbb{R}$ $\sum_{i=1}^{n} |x_{i} - median| \leq \sum_{i=1}^{n} |x_{i} - a|$ and $\sum_{i=1}^{n} (x_{i} - mean)^{2} \leq \sum_{i=1}^{n} (x_{i} - a)^{2}$
Mean and Median properties Roughly speaking, the median is the "middle value". Now, if you change the highest value (which is supposed to be positive here) from $x_{(n)}$ to $2 * x_{(n)}$, say, it does not change the median. B
13,048
Mean and Median properties
Hey here is a contribution, after I read about it a bit. Probably a bit late for the person who asked, but maybe worth for someone else. For the mean case : Consider the problem $argmin_x \sum_{i=1}^n (y_i - x)$ Introduce $f(x) = \sum_{i=1}^n(y_i - x)^2$ $f'(x)=0 \Leftrightarrow 2 \sum_{i=1}^n (y_i - x ) = 0$ $f'(x)=0\Leftrightarrow \sum_{i=1}^n y_i = \sum_{i=1}^n x$ $f'(x)=0\Leftrightarrow x = \frac{\sum_{i=1}^n}{n}$ As the function is convex, this is a minimum For the median case Consider the problem $argmin_x \sum_{i=1}^n |y_i - x|$ Introduce $f(x) = \sum_{i=1}^n|y_i - x|$ $f'(x)=0 \Leftrightarrow \sum_{i=1}^n sgn(y_i - x ) = 0$ (where $sgn(x)$ is the sign of x : $sgn(x)=1$ if $x >0$ and $sgn(x)=-1$ if $x<0$) $f'(x)=0\Leftrightarrow \# \{y_i / y_i >x \} - \# \{y_i / y_i <x \} = 0 $ (where $\#{}$ is the cardinal of the space, so in this discrete case, the number of elements in it) $f'(x)=0\Leftrightarrow x$ is the median if n is odd (you have to refine a bit if it is even, but the principle is the same). As the function is convex too, this is a minimum again.
Mean and Median properties
Hey here is a contribution, after I read about it a bit. Probably a bit late for the person who asked, but maybe worth for someone else. For the mean case : Consider the problem $argmin_x \sum_{i=1}^
Mean and Median properties Hey here is a contribution, after I read about it a bit. Probably a bit late for the person who asked, but maybe worth for someone else. For the mean case : Consider the problem $argmin_x \sum_{i=1}^n (y_i - x)$ Introduce $f(x) = \sum_{i=1}^n(y_i - x)^2$ $f'(x)=0 \Leftrightarrow 2 \sum_{i=1}^n (y_i - x ) = 0$ $f'(x)=0\Leftrightarrow \sum_{i=1}^n y_i = \sum_{i=1}^n x$ $f'(x)=0\Leftrightarrow x = \frac{\sum_{i=1}^n}{n}$ As the function is convex, this is a minimum For the median case Consider the problem $argmin_x \sum_{i=1}^n |y_i - x|$ Introduce $f(x) = \sum_{i=1}^n|y_i - x|$ $f'(x)=0 \Leftrightarrow \sum_{i=1}^n sgn(y_i - x ) = 0$ (where $sgn(x)$ is the sign of x : $sgn(x)=1$ if $x >0$ and $sgn(x)=-1$ if $x<0$) $f'(x)=0\Leftrightarrow \# \{y_i / y_i >x \} - \# \{y_i / y_i <x \} = 0 $ (where $\#{}$ is the cardinal of the space, so in this discrete case, the number of elements in it) $f'(x)=0\Leftrightarrow x$ is the median if n is odd (you have to refine a bit if it is even, but the principle is the same). As the function is convex too, this is a minimum again.
Mean and Median properties Hey here is a contribution, after I read about it a bit. Probably a bit late for the person who asked, but maybe worth for someone else. For the mean case : Consider the problem $argmin_x \sum_{i=1}^
13,049
Why is GLM different than an LM with transformed variable
Transforming the response prior to doing a linear regression is doing this: $$E(g(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is a given function, and we assume that $g(Y)$ has a given distribution (usually normal). A generalised linear model is doing this: $$g(E(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is the same as before, and we assume that $Y$ has a given distribution (usually not normal).
Why is GLM different than an LM with transformed variable
Transforming the response prior to doing a linear regression is doing this: $$E(g(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is a given function, and we assume that $g(Y)$ has a g
Why is GLM different than an LM with transformed variable Transforming the response prior to doing a linear regression is doing this: $$E(g(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is a given function, and we assume that $g(Y)$ has a given distribution (usually normal). A generalised linear model is doing this: $$g(E(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is the same as before, and we assume that $Y$ has a given distribution (usually not normal).
Why is GLM different than an LM with transformed variable Transforming the response prior to doing a linear regression is doing this: $$E(g(Y)) \sim \beta_0 + \beta_1x_1 + \ldots + \beta_px_p$$ where $g$ is a given function, and we assume that $g(Y)$ has a g
13,050
Why is GLM different than an LM with transformed variable
I'm not sure if this will constitute a complete answer for you, but it may help break free the conceptual logjam. There seem to be two misconceptions in your account: Bear in mind that ordinary least squares (OLS--'linear') regression is a special case of the generalized linear model. Thus, when you say "[t]ransforming a response variable does NOT equate to doing a GLM", this is incorrect. Fitting a linear model or transforming the response variable and then fitting a linear model both constitute 'doing a GLM'. In the standard formulation of GLMs, what you call "$u$" (which is often represented by $\mu$, but this is just a matter of preference) is the mean of the conditional response distribution at a specific location in the covariate space (i.e., $X$). Thus, when you say "where $u$ is just another symbol for $y$", this is also incorrect. In the OLS formulation, $Y$ is a random variable and/or $y_i$ is a realized value of $Y$ for observation / study unit $i$. That is, $y$ (more generically) represents data, not a parameter. (I don't mean to be harping on mistakes, I just suspect that these may be causing your confusion.) There is also another aspect of the generalized linear model that I don't see you mentioning. That is that we specify a response distribution. In the case of OLS regression, the response distribution is Gaussian (normal) and the link function is the identity function. In the case of, say, logistic regression (which may be what people first think of when they think of GLMs), the response distribution is the Bernoulli (/ binomial) and the link function is the logit. When using transformations to ensure the assumptions for OLS are met, we are often trying to make the conditional response distribution acceptably normal. However, no such transformation will make the Bernoulli distribution acceptably normal.
Why is GLM different than an LM with transformed variable
I'm not sure if this will constitute a complete answer for you, but it may help break free the conceptual logjam. There seem to be two misconceptions in your account: Bear in mind that ordinary least
Why is GLM different than an LM with transformed variable I'm not sure if this will constitute a complete answer for you, but it may help break free the conceptual logjam. There seem to be two misconceptions in your account: Bear in mind that ordinary least squares (OLS--'linear') regression is a special case of the generalized linear model. Thus, when you say "[t]ransforming a response variable does NOT equate to doing a GLM", this is incorrect. Fitting a linear model or transforming the response variable and then fitting a linear model both constitute 'doing a GLM'. In the standard formulation of GLMs, what you call "$u$" (which is often represented by $\mu$, but this is just a matter of preference) is the mean of the conditional response distribution at a specific location in the covariate space (i.e., $X$). Thus, when you say "where $u$ is just another symbol for $y$", this is also incorrect. In the OLS formulation, $Y$ is a random variable and/or $y_i$ is a realized value of $Y$ for observation / study unit $i$. That is, $y$ (more generically) represents data, not a parameter. (I don't mean to be harping on mistakes, I just suspect that these may be causing your confusion.) There is also another aspect of the generalized linear model that I don't see you mentioning. That is that we specify a response distribution. In the case of OLS regression, the response distribution is Gaussian (normal) and the link function is the identity function. In the case of, say, logistic regression (which may be what people first think of when they think of GLMs), the response distribution is the Bernoulli (/ binomial) and the link function is the logit. When using transformations to ensure the assumptions for OLS are met, we are often trying to make the conditional response distribution acceptably normal. However, no such transformation will make the Bernoulli distribution acceptably normal.
Why is GLM different than an LM with transformed variable I'm not sure if this will constitute a complete answer for you, but it may help break free the conceptual logjam. There seem to be two misconceptions in your account: Bear in mind that ordinary least
13,051
Can I ignore coefficients for non-significant levels of factors in a linear model?
If you are putting in a predictor variable with multiple levels, you either put in the variable or you don't, you can't pick and choose levels. You might want to restructure the levels of your predictor variable to decrease the number of levels (if that makes sense in the context of your analysis.) However, I'm not sure if this would cause some type of statistical invalidation if you're collapsing levels because you see they are not significant. Also, just a note, you say small $p$-values are insignificant. I assume that you meant small $p$-value are significant, ie: a $p$-value of .0001 is significant and therefore you reject the null (assuming an $\alpha$ level of $> .0001$?).
Can I ignore coefficients for non-significant levels of factors in a linear model?
If you are putting in a predictor variable with multiple levels, you either put in the variable or you don't, you can't pick and choose levels. You might want to restructure the levels of your predict
Can I ignore coefficients for non-significant levels of factors in a linear model? If you are putting in a predictor variable with multiple levels, you either put in the variable or you don't, you can't pick and choose levels. You might want to restructure the levels of your predictor variable to decrease the number of levels (if that makes sense in the context of your analysis.) However, I'm not sure if this would cause some type of statistical invalidation if you're collapsing levels because you see they are not significant. Also, just a note, you say small $p$-values are insignificant. I assume that you meant small $p$-value are significant, ie: a $p$-value of .0001 is significant and therefore you reject the null (assuming an $\alpha$ level of $> .0001$?).
Can I ignore coefficients for non-significant levels of factors in a linear model? If you are putting in a predictor variable with multiple levels, you either put in the variable or you don't, you can't pick and choose levels. You might want to restructure the levels of your predict
13,052
Can I ignore coefficients for non-significant levels of factors in a linear model?
@Ellie's response is a good one. If you are putting in a variable with a number of levels, you need to retain all those levels in your analysis. Picking and choosing based on significance level will both bias your results and do very weird things to your inference, even if by some miracle your estimates manage to stay the same, as you'll have gaping holes in your estimated effects over different levels of the variable. I would consider looking at your estimates for each level of the predictor graphically. Are you seeing a trend as you go up levels, or is it erratic? Generally speaking, I'm also opposed to recoding variables based on statistical tests - or based purely on statistical moments. The divisions in your variable should be based on something more firm - logically meaningful cut-points, field interest in a particular transition point, etc.
Can I ignore coefficients for non-significant levels of factors in a linear model?
@Ellie's response is a good one. If you are putting in a variable with a number of levels, you need to retain all those levels in your analysis. Picking and choosing based on significance level will b
Can I ignore coefficients for non-significant levels of factors in a linear model? @Ellie's response is a good one. If you are putting in a variable with a number of levels, you need to retain all those levels in your analysis. Picking and choosing based on significance level will both bias your results and do very weird things to your inference, even if by some miracle your estimates manage to stay the same, as you'll have gaping holes in your estimated effects over different levels of the variable. I would consider looking at your estimates for each level of the predictor graphically. Are you seeing a trend as you go up levels, or is it erratic? Generally speaking, I'm also opposed to recoding variables based on statistical tests - or based purely on statistical moments. The divisions in your variable should be based on something more firm - logically meaningful cut-points, field interest in a particular transition point, etc.
Can I ignore coefficients for non-significant levels of factors in a linear model? @Ellie's response is a good one. If you are putting in a variable with a number of levels, you need to retain all those levels in your analysis. Picking and choosing based on significance level will b
13,053
Can I ignore coefficients for non-significant levels of factors in a linear model?
Expanding on the two good answers you've already gotten, let's look at this substantively. Suppose your dependent variable is (say) income and your independent variable is (say) ethnicity, with levels, per census definitions (White, Black/Afr.Am., Am. Indian/Alaska Native, Asian, Native Hawaii/Pac Islander, other and multiracial). Let's say you dummy code it with White being the reference category and you get $ Income = b_0 + b_1BAA + b_2AIAN + b_3AS + b_4NHPI + b_5O + b_6MR $ If you are doing this study in New York City, you will probably get very few Native Hawaiians/Pacific Islanders. You might decide to include them (if there are any) with the others. However, you can't use the full equation and just not include that coefficient. Then the intercept will be wrong, and so will any predicted values for income. But how should you combine categories? As the others said, it has to make sense.
Can I ignore coefficients for non-significant levels of factors in a linear model?
Expanding on the two good answers you've already gotten, let's look at this substantively. Suppose your dependent variable is (say) income and your independent variable is (say) ethnicity, with levels
Can I ignore coefficients for non-significant levels of factors in a linear model? Expanding on the two good answers you've already gotten, let's look at this substantively. Suppose your dependent variable is (say) income and your independent variable is (say) ethnicity, with levels, per census definitions (White, Black/Afr.Am., Am. Indian/Alaska Native, Asian, Native Hawaii/Pac Islander, other and multiracial). Let's say you dummy code it with White being the reference category and you get $ Income = b_0 + b_1BAA + b_2AIAN + b_3AS + b_4NHPI + b_5O + b_6MR $ If you are doing this study in New York City, you will probably get very few Native Hawaiians/Pacific Islanders. You might decide to include them (if there are any) with the others. However, you can't use the full equation and just not include that coefficient. Then the intercept will be wrong, and so will any predicted values for income. But how should you combine categories? As the others said, it has to make sense.
Can I ignore coefficients for non-significant levels of factors in a linear model? Expanding on the two good answers you've already gotten, let's look at this substantively. Suppose your dependent variable is (say) income and your independent variable is (say) ethnicity, with levels
13,054
Can I ignore coefficients for non-significant levels of factors in a linear model?
To give a different opinion: why not include it as a random effect? That should penalize those levels with weak support and make sure their effect size is minimal. That way you can keep them all in without worrying about getting silly predictions. And yes, this is more motivated from a Bayesian view of random effects than the whole "sample of all possible levels" view of random effects.
Can I ignore coefficients for non-significant levels of factors in a linear model?
To give a different opinion: why not include it as a random effect? That should penalize those levels with weak support and make sure their effect size is minimal. That way you can keep them all in
Can I ignore coefficients for non-significant levels of factors in a linear model? To give a different opinion: why not include it as a random effect? That should penalize those levels with weak support and make sure their effect size is minimal. That way you can keep them all in without worrying about getting silly predictions. And yes, this is more motivated from a Bayesian view of random effects than the whole "sample of all possible levels" view of random effects.
Can I ignore coefficients for non-significant levels of factors in a linear model? To give a different opinion: why not include it as a random effect? That should penalize those levels with weak support and make sure their effect size is minimal. That way you can keep them all in
13,055
Can I ignore coefficients for non-significant levels of factors in a linear model?
I was also wondering whether I could combine non-significant categories with the reference category. The following statements in the book "Data Mining for Business Intelligence: Concepts, Techniques, and Applications in Microsoft Office Excel® with XLMiner®, 2nd Edition by Galit Shmueli, Nitin R. Patel, Peter C. Bruce", p87-89 (Dimension Reduction section) (Google Search Result) seem to support the second sentence of @Ellie's response: "Fitted regression models can also be used to further combine similar categories: categories that have coefficients that are not statistically significant (i.e. have a high p-value) can be combined with the reference category because their distinction from the reference category appears to have no significant effect on the output variable" "Categories that have similar coefficient values (and the same sign) can often be combined because their effect on the output variable is similar" However, I plan to check with subject matter experts whether combining the categories makes logical sense (as implied in previous answers / comments, e.g. @Fomite, @gung).
Can I ignore coefficients for non-significant levels of factors in a linear model?
I was also wondering whether I could combine non-significant categories with the reference category. The following statements in the book "Data Mining for Business Intelligence: Concepts, Techniques,
Can I ignore coefficients for non-significant levels of factors in a linear model? I was also wondering whether I could combine non-significant categories with the reference category. The following statements in the book "Data Mining for Business Intelligence: Concepts, Techniques, and Applications in Microsoft Office Excel® with XLMiner®, 2nd Edition by Galit Shmueli, Nitin R. Patel, Peter C. Bruce", p87-89 (Dimension Reduction section) (Google Search Result) seem to support the second sentence of @Ellie's response: "Fitted regression models can also be used to further combine similar categories: categories that have coefficients that are not statistically significant (i.e. have a high p-value) can be combined with the reference category because their distinction from the reference category appears to have no significant effect on the output variable" "Categories that have similar coefficient values (and the same sign) can often be combined because their effect on the output variable is similar" However, I plan to check with subject matter experts whether combining the categories makes logical sense (as implied in previous answers / comments, e.g. @Fomite, @gung).
Can I ignore coefficients for non-significant levels of factors in a linear model? I was also wondering whether I could combine non-significant categories with the reference category. The following statements in the book "Data Mining for Business Intelligence: Concepts, Techniques,
13,056
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate]
Here is an intuitive argument with light math. Let's say we have a $d$ claiming to be minimizing the MAE of points $x_i$. And, let's say we have $n_l$ and $n_r$ points on its left and right. If we move $d$ slightly left, i.e. an amount of $\Delta$, then all the absolute differences on the left will decrease by $\Delta$, and all the absolute differences on the right will increase by $\Delta$, leading to a net decrease of $(n_l-n_r)\Delta$ in MAE. If $n_l\neq n_r$, $d$ always have incentive to move either left or right, because each move either decreases or increases the MAE. For example, if $n_r<n_l$, then we move left because the net decrease in MAE is $(n_l-n_r)\Delta$, and if $n_l<n_r$ we move right because the net decrease will be $(n_r-n_l)\Delta$. This continues until we reach $n_l=n_r$, which is satisfied by the median.
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate]
Here is an intuitive argument with light math. Let's say we have a $d$ claiming to be minimizing the MAE of points $x_i$. And, let's say we have $n_l$ and $n_r$ points on its left and right. If we mov
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate] Here is an intuitive argument with light math. Let's say we have a $d$ claiming to be minimizing the MAE of points $x_i$. And, let's say we have $n_l$ and $n_r$ points on its left and right. If we move $d$ slightly left, i.e. an amount of $\Delta$, then all the absolute differences on the left will decrease by $\Delta$, and all the absolute differences on the right will increase by $\Delta$, leading to a net decrease of $(n_l-n_r)\Delta$ in MAE. If $n_l\neq n_r$, $d$ always have incentive to move either left or right, because each move either decreases or increases the MAE. For example, if $n_r<n_l$, then we move left because the net decrease in MAE is $(n_l-n_r)\Delta$, and if $n_l<n_r$ we move right because the net decrease will be $(n_r-n_l)\Delta$. This continues until we reach $n_l=n_r$, which is satisfied by the median.
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate] Here is an intuitive argument with light math. Let's say we have a $d$ claiming to be minimizing the MAE of points $x_i$. And, let's say we have $n_l$ and $n_r$ points on its left and right. If we mov
13,057
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate]
gunes has already presented a wonderful answer with simple formulas. Here is my a numerical example to test it: consider the set {1, 1, 1, 1, 1, 1, 1, 1, 1, 11}; that is, nine 1s and a single 11. The mean is 2, the median is 1. When you consider the sum of absolute values as the sum of distances, the median will have 0 distance to nine values but a distance of 10 to the final value, making a total sum of 10. By moving our comparison value a single unit to 2 (the mean), we will increase the sum of distances by 1 from each of the nine values and decrease it by 1 from the single final value, making a total sum of 17. Applying the formulas from gunes, when you move right from the median by any small value of $\Delta$, you add $9 * \Delta$ and subtract $1 * \Delta$, which means the sum increases by a total of $8 * \Delta$. If you move left then the sum increases by a total of $10 * \Delta$. By intuition, you stop moving left or right when the number of values to the left and to the right are equal. This can be the median (middle value) for an odd number of values or anywhere between the two middle values when there are an even number of values. To demonstrate the final point: consider the set {1, 2, 3, 4}. Here the median is 2.5 by definition. But you can use an point between the two middle values (inclusive) of 2 and 3. The sum of distances would be 4 for the [2, 3] range (for 2, 2.5, 3, or anything in between).
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate]
gunes has already presented a wonderful answer with simple formulas. Here is my a numerical example to test it: consider the set {1, 1, 1, 1, 1, 1, 1, 1, 1, 11}; that is, nine 1s and a single 11. The
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate] gunes has already presented a wonderful answer with simple formulas. Here is my a numerical example to test it: consider the set {1, 1, 1, 1, 1, 1, 1, 1, 1, 11}; that is, nine 1s and a single 11. The mean is 2, the median is 1. When you consider the sum of absolute values as the sum of distances, the median will have 0 distance to nine values but a distance of 10 to the final value, making a total sum of 10. By moving our comparison value a single unit to 2 (the mean), we will increase the sum of distances by 1 from each of the nine values and decrease it by 1 from the single final value, making a total sum of 17. Applying the formulas from gunes, when you move right from the median by any small value of $\Delta$, you add $9 * \Delta$ and subtract $1 * \Delta$, which means the sum increases by a total of $8 * \Delta$. If you move left then the sum increases by a total of $10 * \Delta$. By intuition, you stop moving left or right when the number of values to the left and to the right are equal. This can be the median (middle value) for an odd number of values or anywhere between the two middle values when there are an even number of values. To demonstrate the final point: consider the set {1, 2, 3, 4}. Here the median is 2.5 by definition. But you can use an point between the two middle values (inclusive) of 2 and 3. The sum of distances would be 4 for the [2, 3] range (for 2, 2.5, 3, or anything in between).
Can someone give the intuition behind Mean Absolute Error and the Median? [duplicate] gunes has already presented a wonderful answer with simple formulas. Here is my a numerical example to test it: consider the set {1, 1, 1, 1, 1, 1, 1, 1, 1, 11}; that is, nine 1s and a single 11. The
13,058
Are there any versions of t-SNE for streaming data?
I had exactly the same question and posted it on a YouTube video of a CS231n lecture given by Andrej Karpathy a few weeks ago. Here is the question I posted followed by Andrej' response: https://www.youtube.com/watch?v=ta5fdaqDT3M&lc=z12ji3arguzwgxdm422gxnf54xaluzhcx Q: Does t-SNE need an entire batch of images (or more generally, data) to create the low-dimensional feature space? With PCA you can create a low-dimensional feature space on a batch of data and then project new data points onto that same space without having to "retrain". Is that true for t-SNE? I ask because I noticed that scikit-learn has t-SNE as part of its manifold class, but that module does not have a transform() method as PCA does. So, at least, in sklearn, it would seem this is not possible. My question boils down to this. How would you apply t-SNE in a streaming or online situation where you want to continually update the visualization with new images? Presumably, one would not want to apply the algorithm on the entire batch for each new image. A: +Evan Zamir yes this is possible with t-SNE, but maybe not supported out of the box with regular t-SNE implementations. Normally each point's location is a parameter in the optimization, but you can just as well create a mapping from high-D -> low-D (e.g. neural net) and backprop through the locations. Then you end up with the embedding function and can project new points. So nothing preventing this in principle, but some implementations might not support it as it's a less frequent use case.
Are there any versions of t-SNE for streaming data?
I had exactly the same question and posted it on a YouTube video of a CS231n lecture given by Andrej Karpathy a few weeks ago. Here is the question I posted followed by Andrej' response: https://www.y
Are there any versions of t-SNE for streaming data? I had exactly the same question and posted it on a YouTube video of a CS231n lecture given by Andrej Karpathy a few weeks ago. Here is the question I posted followed by Andrej' response: https://www.youtube.com/watch?v=ta5fdaqDT3M&lc=z12ji3arguzwgxdm422gxnf54xaluzhcx Q: Does t-SNE need an entire batch of images (or more generally, data) to create the low-dimensional feature space? With PCA you can create a low-dimensional feature space on a batch of data and then project new data points onto that same space without having to "retrain". Is that true for t-SNE? I ask because I noticed that scikit-learn has t-SNE as part of its manifold class, but that module does not have a transform() method as PCA does. So, at least, in sklearn, it would seem this is not possible. My question boils down to this. How would you apply t-SNE in a streaming or online situation where you want to continually update the visualization with new images? Presumably, one would not want to apply the algorithm on the entire batch for each new image. A: +Evan Zamir yes this is possible with t-SNE, but maybe not supported out of the box with regular t-SNE implementations. Normally each point's location is a parameter in the optimization, but you can just as well create a mapping from high-D -> low-D (e.g. neural net) and backprop through the locations. Then you end up with the embedding function and can project new points. So nothing preventing this in principle, but some implementations might not support it as it's a less frequent use case.
Are there any versions of t-SNE for streaming data? I had exactly the same question and posted it on a YouTube video of a CS231n lecture given by Andrej Karpathy a few weeks ago. Here is the question I posted followed by Andrej' response: https://www.y
13,059
Are there any versions of t-SNE for streaming data?
When dealing with streaming data, you might not want/need to embed all the points in history in a single t-SNE map. As an alternative, you can perform an online embedding by following these simple steps: choose a time-window of duration T, long enough so that each pattern of interest appears at least a couple of times in the window duration. scroll the window as the data streams in, with a time-step dt much smaller than T. For each position of the window, compute a t-SNE embedding of the data points in the time window. seed each embedding with the outcome of the previous one. In t-SNE, one needs to choose the initial coordinates of the data points in the low-dimensional space. In our case, because we choose dt much smaller than T, two successive embeddings share most of their data points. For all the shared data points, match their initial coordinates in the present embedding to their final coordinates in the previous embedding. This step will ensure that similar patterns have a consistent representation across successive embeddings. (in the sklearn implementation in python, the seed parameter is "init". By default, the sklearn implementation sets the initial position of the points randomly) Note 1: It is important that the patterns of interest appear at least once in any given time window, so that the memory of the representation does not get lost as the window slides through the dataset. Indeed, t-SNE typically does not converge to a unique solution but only to a local minimum, so if the memory is lost, a similar pattern might be represented in very different ways in two instanciations of an embedding. Note 2: This method is particularly relevant when dealing with non-stationary time series, where one wishes to track patterns that evolve slowly through time. Indeed, each embedding is here taylored specifically to the small time window on which it is computed, ensuring that it captures temporally local structure in the best way (contrarily to a full embedding of the whole non-stationary dataset). Note 3: In this method the successive embeddings cannot be parallelized, because one needs the outcome of the previous embedding in order to seed the next one. However, because the seed (i.e. initial coordinates of the points) is well chosen for most points (all shared points between succesive embeddings), an embedding typically converges very fast, in a few iterations only. For an example of application of this method to non-stationary time series, see this article (ICLR 2016, Learning stable representations in a changing world with on-line t-SNE: proof of concept in the songbird), where it was successfully applied to track the emergence of syllables across development in the songbird.
Are there any versions of t-SNE for streaming data?
When dealing with streaming data, you might not want/need to embed all the points in history in a single t-SNE map. As an alternative, you can perform an online embedding by following these simple ste
Are there any versions of t-SNE for streaming data? When dealing with streaming data, you might not want/need to embed all the points in history in a single t-SNE map. As an alternative, you can perform an online embedding by following these simple steps: choose a time-window of duration T, long enough so that each pattern of interest appears at least a couple of times in the window duration. scroll the window as the data streams in, with a time-step dt much smaller than T. For each position of the window, compute a t-SNE embedding of the data points in the time window. seed each embedding with the outcome of the previous one. In t-SNE, one needs to choose the initial coordinates of the data points in the low-dimensional space. In our case, because we choose dt much smaller than T, two successive embeddings share most of their data points. For all the shared data points, match their initial coordinates in the present embedding to their final coordinates in the previous embedding. This step will ensure that similar patterns have a consistent representation across successive embeddings. (in the sklearn implementation in python, the seed parameter is "init". By default, the sklearn implementation sets the initial position of the points randomly) Note 1: It is important that the patterns of interest appear at least once in any given time window, so that the memory of the representation does not get lost as the window slides through the dataset. Indeed, t-SNE typically does not converge to a unique solution but only to a local minimum, so if the memory is lost, a similar pattern might be represented in very different ways in two instanciations of an embedding. Note 2: This method is particularly relevant when dealing with non-stationary time series, where one wishes to track patterns that evolve slowly through time. Indeed, each embedding is here taylored specifically to the small time window on which it is computed, ensuring that it captures temporally local structure in the best way (contrarily to a full embedding of the whole non-stationary dataset). Note 3: In this method the successive embeddings cannot be parallelized, because one needs the outcome of the previous embedding in order to seed the next one. However, because the seed (i.e. initial coordinates of the points) is well chosen for most points (all shared points between succesive embeddings), an embedding typically converges very fast, in a few iterations only. For an example of application of this method to non-stationary time series, see this article (ICLR 2016, Learning stable representations in a changing world with on-line t-SNE: proof of concept in the songbird), where it was successfully applied to track the emergence of syllables across development in the songbird.
Are there any versions of t-SNE for streaming data? When dealing with streaming data, you might not want/need to embed all the points in history in a single t-SNE map. As an alternative, you can perform an online embedding by following these simple ste
13,060
Are there any versions of t-SNE for streaming data?
There is a recently published variant, called A-tSNE, which supports dynamically adding new data and refining clusters either based on interest areas or by user input. The paper linked below has some pretty nice examples of this: Citation: arXiv:1512.01655 Approximated and User Steerable tSNE for Progressive Visual Analytics Nicola Pezzotti, Boudewijn P.F. Lelieveldt, Laurens van der Maaten, Thomas Höllt, Elmar Eisemann, Anna Vilanova Summary: Progressive Visual Analytics aims at improving the interactivity in existing analytics techniques by means of visualization as well as interaction with intermediate results. One key method for data analysis is dimensionality reduction, for example, to produce 2D embeddings that can be visualized and analyzed efficiently. t-Distributed Stochastic Neighbor Embedding (tSNE) is a well-suited technique for the visualization of several high-dimensional data. tSNE can create meaningful intermediate results but suffers from a slow initialization that constrains its application in Progressive Visual Analytics. We introduce a controllable tSNE approximation (A-tSNE), which trades off speed and accuracy, to enable interactive data exploration. We offer real-time visualization techniques, including a density-based solution and a Magic Lens to inspect the degree of approximation. With this feedback, the user can decide on local refinements and steer the approximation level during the analysis. We demonstrate our technique with several datasets, in a real-world research scenario and for the real-time analysis of high-dimensional streams to illustrate its effectiveness for interactive data analysis.
Are there any versions of t-SNE for streaming data?
There is a recently published variant, called A-tSNE, which supports dynamically adding new data and refining clusters either based on interest areas or by user input. The paper linked below has some
Are there any versions of t-SNE for streaming data? There is a recently published variant, called A-tSNE, which supports dynamically adding new data and refining clusters either based on interest areas or by user input. The paper linked below has some pretty nice examples of this: Citation: arXiv:1512.01655 Approximated and User Steerable tSNE for Progressive Visual Analytics Nicola Pezzotti, Boudewijn P.F. Lelieveldt, Laurens van der Maaten, Thomas Höllt, Elmar Eisemann, Anna Vilanova Summary: Progressive Visual Analytics aims at improving the interactivity in existing analytics techniques by means of visualization as well as interaction with intermediate results. One key method for data analysis is dimensionality reduction, for example, to produce 2D embeddings that can be visualized and analyzed efficiently. t-Distributed Stochastic Neighbor Embedding (tSNE) is a well-suited technique for the visualization of several high-dimensional data. tSNE can create meaningful intermediate results but suffers from a slow initialization that constrains its application in Progressive Visual Analytics. We introduce a controllable tSNE approximation (A-tSNE), which trades off speed and accuracy, to enable interactive data exploration. We offer real-time visualization techniques, including a density-based solution and a Magic Lens to inspect the degree of approximation. With this feedback, the user can decide on local refinements and steer the approximation level during the analysis. We demonstrate our technique with several datasets, in a real-world research scenario and for the real-time analysis of high-dimensional streams to illustrate its effectiveness for interactive data analysis.
Are there any versions of t-SNE for streaming data? There is a recently published variant, called A-tSNE, which supports dynamically adding new data and refining clusters either based on interest areas or by user input. The paper linked below has some
13,061
Are there any versions of t-SNE for streaming data?
The Barnes-Hut approximation makes t-SNE highly scalable (at least, you can use it with 100 000 lines, I tried it). You can call it from R : Rtsne The complexity of the implemented algorithm is $O(n\log(n))$ whereas the naive implementation had a complexity of $O(n^2)$. The details of the underlying approximation can be found here Accelerating t-SNE using Tree-Based Algorithms.
Are there any versions of t-SNE for streaming data?
The Barnes-Hut approximation makes t-SNE highly scalable (at least, you can use it with 100 000 lines, I tried it). You can call it from R : Rtsne The complexity of the implemented algorithm is $O(n\l
Are there any versions of t-SNE for streaming data? The Barnes-Hut approximation makes t-SNE highly scalable (at least, you can use it with 100 000 lines, I tried it). You can call it from R : Rtsne The complexity of the implemented algorithm is $O(n\log(n))$ whereas the naive implementation had a complexity of $O(n^2)$. The details of the underlying approximation can be found here Accelerating t-SNE using Tree-Based Algorithms.
Are there any versions of t-SNE for streaming data? The Barnes-Hut approximation makes t-SNE highly scalable (at least, you can use it with 100 000 lines, I tried it). You can call it from R : Rtsne The complexity of the implemented algorithm is $O(n\l
13,062
Are there any versions of t-SNE for streaming data?
Barnes-Hut approximation is now the default method in scikit-learn as of version 0.17.0: By default the gradient calculation algorithm uses Barnes-Hut approximation running in O(NlogN) time. method=’exact’ will run on the slower, but exact, algorithm in O(N^2) time. The exact algorithm should be used when nearest-neighbor errors need to be better than 3%. However, the exact method cannot scale to millions of examples. New in version 0.17: Approximate optimization method via the Barnes-Hut.
Are there any versions of t-SNE for streaming data?
Barnes-Hut approximation is now the default method in scikit-learn as of version 0.17.0: By default the gradient calculation algorithm uses Barnes-Hut approximation running in O(NlogN) time. method
Are there any versions of t-SNE for streaming data? Barnes-Hut approximation is now the default method in scikit-learn as of version 0.17.0: By default the gradient calculation algorithm uses Barnes-Hut approximation running in O(NlogN) time. method=’exact’ will run on the slower, but exact, algorithm in O(N^2) time. The exact algorithm should be used when nearest-neighbor errors need to be better than 3%. However, the exact method cannot scale to millions of examples. New in version 0.17: Approximate optimization method via the Barnes-Hut.
Are there any versions of t-SNE for streaming data? Barnes-Hut approximation is now the default method in scikit-learn as of version 0.17.0: By default the gradient calculation algorithm uses Barnes-Hut approximation running in O(NlogN) time. method
13,063
Meaning of completeness of a statistic? [duplicate]
This is a very good question and one I've struggled with for quite some time. Here's how I've decided to think about it: Take the contrapositive of the definition as stated in Wikipedia (which doesn't change the logical meaning at all): \begin{align} {\rm If}\quad &\neg\ \forall \theta\ P(g(T(x))=0)=1 \\ {\rm then}\quad &\neg\ \forall \theta\ E(g(T(x))) = 0 \end{align} In other words, if there is a parameter value such that $g(T(x))$ is not almost surely $0$, then there is a parameter value such that the expected value of that statistic is not $0$. Hmm. What does that even mean? Let's ask what happens when $T(x)$ is NOT complete... A statistic $T(x)$ that is NOT complete will have at least one parameter value such that $g(T(x))$ is not almost surely $0$ for that value, and yet it's expected value is $0$ for all parameter values (including this one). In other words, there are values of $\theta$ for which $g(T(x))$ has a non-trivial distribution around it (it has some random variation in it), and yet the expected value of $g(T(x))$ is nonetheless always $0$--it doesn't budge, no matter how much $\theta$ is different. A complete statistic, on the other have, will budge in it's expected value eventually if $g(T(x))$ is non-trivially distributed and centered at $0$ for some $\theta$. Put another way, if we find a function $g(\cdot)$ where the expected value is zero for some $\theta$ value (say $\theta_0$) and it has a non-trivial distribution given that value of $\theta$, then there must be another value of $\theta$ out there (say, $\theta_1 \ne \theta_0$) that results in a different expectation for $g(T(x))$. This means we can actually use this statistic for hypothesis testing and informative estimation in the context of an assumed distribution for our data. We want to be able to center it around a hypothesized value of $\theta$ and get it to have expectation 0 for that hypothesized value of $\theta$, but not for all other values of $\theta$. But if the statistic is not complete we may not be able to do this: we may be unable to reject any hypothesized values of $\theta$. But then we can't build confidence intervals and do statistical estimation.
Meaning of completeness of a statistic? [duplicate]
This is a very good question and one I've struggled with for quite some time. Here's how I've decided to think about it: Take the contrapositive of the definition as stated in Wikipedia (which doesn't
Meaning of completeness of a statistic? [duplicate] This is a very good question and one I've struggled with for quite some time. Here's how I've decided to think about it: Take the contrapositive of the definition as stated in Wikipedia (which doesn't change the logical meaning at all): \begin{align} {\rm If}\quad &\neg\ \forall \theta\ P(g(T(x))=0)=1 \\ {\rm then}\quad &\neg\ \forall \theta\ E(g(T(x))) = 0 \end{align} In other words, if there is a parameter value such that $g(T(x))$ is not almost surely $0$, then there is a parameter value such that the expected value of that statistic is not $0$. Hmm. What does that even mean? Let's ask what happens when $T(x)$ is NOT complete... A statistic $T(x)$ that is NOT complete will have at least one parameter value such that $g(T(x))$ is not almost surely $0$ for that value, and yet it's expected value is $0$ for all parameter values (including this one). In other words, there are values of $\theta$ for which $g(T(x))$ has a non-trivial distribution around it (it has some random variation in it), and yet the expected value of $g(T(x))$ is nonetheless always $0$--it doesn't budge, no matter how much $\theta$ is different. A complete statistic, on the other have, will budge in it's expected value eventually if $g(T(x))$ is non-trivially distributed and centered at $0$ for some $\theta$. Put another way, if we find a function $g(\cdot)$ where the expected value is zero for some $\theta$ value (say $\theta_0$) and it has a non-trivial distribution given that value of $\theta$, then there must be another value of $\theta$ out there (say, $\theta_1 \ne \theta_0$) that results in a different expectation for $g(T(x))$. This means we can actually use this statistic for hypothesis testing and informative estimation in the context of an assumed distribution for our data. We want to be able to center it around a hypothesized value of $\theta$ and get it to have expectation 0 for that hypothesized value of $\theta$, but not for all other values of $\theta$. But if the statistic is not complete we may not be able to do this: we may be unable to reject any hypothesized values of $\theta$. But then we can't build confidence intervals and do statistical estimation.
Meaning of completeness of a statistic? [duplicate] This is a very good question and one I've struggled with for quite some time. Here's how I've decided to think about it: Take the contrapositive of the definition as stated in Wikipedia (which doesn't
13,064
Meaning of completeness of a statistic? [duplicate]
Geometrically, completeness means something like this: if a vector $g(T)$ is orthogonal to the p.d.f. $f_\theta$ of $T$ for each $\theta$, $$\mathbb E_\theta g(T) = \langle g(T),f_\theta\rangle=0$$ then $g(T)=0$ i.e., the functions $f_\theta$ for varying $\theta$ span the whole space of functions of $T$. So in a way it would be more natural to say that $\theta$ is complete for $T$ than what we do say, $T$ is complete for $\theta$. This way it is not so strange that a constant function would be "complete"! Maybe an example helps. Suppose $X$ and $Y$ are independent and identically distributed Bernoulli($\theta$) random variables taking values in $\{0,1\}$, and $Z=X-Y$. Then $Z$ is incomplete for $\theta$, because taking $g=\text{identity}$, $$\mathbb E_\theta(Z)=0$$ for all $0<\theta<1$, but nevertheless $\mathbb P_\theta(Z=0)\ne 1$.
Meaning of completeness of a statistic? [duplicate]
Geometrically, completeness means something like this: if a vector $g(T)$ is orthogonal to the p.d.f. $f_\theta$ of $T$ for each $\theta$, $$\mathbb E_\theta g(T) = \langle g(T),f_\theta\rangle=0$$ th
Meaning of completeness of a statistic? [duplicate] Geometrically, completeness means something like this: if a vector $g(T)$ is orthogonal to the p.d.f. $f_\theta$ of $T$ for each $\theta$, $$\mathbb E_\theta g(T) = \langle g(T),f_\theta\rangle=0$$ then $g(T)=0$ i.e., the functions $f_\theta$ for varying $\theta$ span the whole space of functions of $T$. So in a way it would be more natural to say that $\theta$ is complete for $T$ than what we do say, $T$ is complete for $\theta$. This way it is not so strange that a constant function would be "complete"! Maybe an example helps. Suppose $X$ and $Y$ are independent and identically distributed Bernoulli($\theta$) random variables taking values in $\{0,1\}$, and $Z=X-Y$. Then $Z$ is incomplete for $\theta$, because taking $g=\text{identity}$, $$\mathbb E_\theta(Z)=0$$ for all $0<\theta<1$, but nevertheless $\mathbb P_\theta(Z=0)\ne 1$.
Meaning of completeness of a statistic? [duplicate] Geometrically, completeness means something like this: if a vector $g(T)$ is orthogonal to the p.d.f. $f_\theta$ of $T$ for each $\theta$, $$\mathbb E_\theta g(T) = \langle g(T),f_\theta\rangle=0$$ th
13,065
Meaning of completeness of a statistic? [duplicate]
I found this very helpful: Definition: A statistic $T$ is called complete if $E_\theta[g(T)] = 0$ for all $\theta$ and some function $g$ implies that $P_\theta(g(T) = 0) = 1$ for all $\theta$. Think of this as analog to vectors and whether or not the vectors {$v_1, \ldots , v_n$} form a complete set (=basis) of the vector space. If they span the whole space, any $v$ can be written as a linear combination of these vectors: $v = \sum_j a_j \cdot v_j$. Furthermore, if a vector $w$ is orthogonal to all $v_j$’s, then $w = 0$. To make the connection with the completeness definition, let’s consider the case of a discrete probability distribution. We start by writing out the completeness condition $$ 0 = E_\theta[g(t)] = \sum_t g(t) \cdot P_\theta(T = t) = \sum_j g(t_j) \cdot P_\theta(T = t_j) = \begin{bmatrix} g(t_1)\\ g(t_2)\\ \ldots \\ g(t_n)\\ \end{bmatrix} \cdot \begin{bmatrix} p_\theta(t_1)\\ p_\theta(t_2)\\ \ldots \\ p_\theta(t_n)\\ \end{bmatrix} $$ for all $\theta$. Here we expressed the sum as a scalar product of two vectors $$(g(t_1), g(t_2),...)$$ and $$(p_\theta(t_1), p_\theta(t_2),...)$$, with $p_\theta(t_j) = P_\theta(T = t_j) \ne 0$ -- we consider only positive probabilities, because if $p(t_j) = 0$ this does not tell us anything about the function $g(t_j)$. Now we see the analogy to the orthogonality condition discussed above. In principle it could be that the $g(t_j)$'s are non-zero, but that they sum to zero. However, as stated by Lhunt, this is only possible if the probability vector $(p_\theta(t_1), p_\theta(t_2),...)$ does either not change at all if $\theta$ is varied, or if it changes in a "simple way", e.g. it jumps from one value for all $j$'s to an other value for all $j$'s, or if it changes in a "correlated way", which would be a nightmare to handle. Thus, the cross-cancelation of terms is only possible if the probability distribution provides either a "boring set of basis vectors" or a nightmare. In contrast, if the probability distribution provides a "sufficient rich set of basis vectors", the equation for the expectation value implies $g(t_j) = 0$ almost everywhere. By almost everywhere we mean, that there could be a set of probability zero, where $g(t_j) \ne 0$ -- e.g. in the case of a continuous probability distribution this could be a set of single points. We also see that the terminology is somewhat misleading. It would be more accurate to call the family of distributions $p_\theta(\cdot)$ complete (rather than the statistic $T$) -- as stated in the original question. In any event, completeness means that the collection of distributions for all possible values of $\theta$ provides a sufficiently rich set of vectors.
Meaning of completeness of a statistic? [duplicate]
I found this very helpful: Definition: A statistic $T$ is called complete if $E_\theta[g(T)] = 0$ for all $\theta$ and some function $g$ implies that $P_\theta(g(T) = 0) = 1$ for all $\theta$. Think
Meaning of completeness of a statistic? [duplicate] I found this very helpful: Definition: A statistic $T$ is called complete if $E_\theta[g(T)] = 0$ for all $\theta$ and some function $g$ implies that $P_\theta(g(T) = 0) = 1$ for all $\theta$. Think of this as analog to vectors and whether or not the vectors {$v_1, \ldots , v_n$} form a complete set (=basis) of the vector space. If they span the whole space, any $v$ can be written as a linear combination of these vectors: $v = \sum_j a_j \cdot v_j$. Furthermore, if a vector $w$ is orthogonal to all $v_j$’s, then $w = 0$. To make the connection with the completeness definition, let’s consider the case of a discrete probability distribution. We start by writing out the completeness condition $$ 0 = E_\theta[g(t)] = \sum_t g(t) \cdot P_\theta(T = t) = \sum_j g(t_j) \cdot P_\theta(T = t_j) = \begin{bmatrix} g(t_1)\\ g(t_2)\\ \ldots \\ g(t_n)\\ \end{bmatrix} \cdot \begin{bmatrix} p_\theta(t_1)\\ p_\theta(t_2)\\ \ldots \\ p_\theta(t_n)\\ \end{bmatrix} $$ for all $\theta$. Here we expressed the sum as a scalar product of two vectors $$(g(t_1), g(t_2),...)$$ and $$(p_\theta(t_1), p_\theta(t_2),...)$$, with $p_\theta(t_j) = P_\theta(T = t_j) \ne 0$ -- we consider only positive probabilities, because if $p(t_j) = 0$ this does not tell us anything about the function $g(t_j)$. Now we see the analogy to the orthogonality condition discussed above. In principle it could be that the $g(t_j)$'s are non-zero, but that they sum to zero. However, as stated by Lhunt, this is only possible if the probability vector $(p_\theta(t_1), p_\theta(t_2),...)$ does either not change at all if $\theta$ is varied, or if it changes in a "simple way", e.g. it jumps from one value for all $j$'s to an other value for all $j$'s, or if it changes in a "correlated way", which would be a nightmare to handle. Thus, the cross-cancelation of terms is only possible if the probability distribution provides either a "boring set of basis vectors" or a nightmare. In contrast, if the probability distribution provides a "sufficient rich set of basis vectors", the equation for the expectation value implies $g(t_j) = 0$ almost everywhere. By almost everywhere we mean, that there could be a set of probability zero, where $g(t_j) \ne 0$ -- e.g. in the case of a continuous probability distribution this could be a set of single points. We also see that the terminology is somewhat misleading. It would be more accurate to call the family of distributions $p_\theta(\cdot)$ complete (rather than the statistic $T$) -- as stated in the original question. In any event, completeness means that the collection of distributions for all possible values of $\theta$ provides a sufficiently rich set of vectors.
Meaning of completeness of a statistic? [duplicate] I found this very helpful: Definition: A statistic $T$ is called complete if $E_\theta[g(T)] = 0$ for all $\theta$ and some function $g$ implies that $P_\theta(g(T) = 0) = 1$ for all $\theta$. Think
13,066
What is the difference between online and batch Learning? [duplicate]
To me it looks like they are using batch and online learning correctly. In section 3 they are working on the whole dataset to perform learning, i.e., batch learning, while in section 4 they switch to stochastic gradient following which can be used as an online learning algorithm. I've never used stochastic gradient following as an online learning algorithm; however, it is possible to simply stop the optimization process in the middle of a learning run and it still being a useful model. For very big datasets this is useful since you can measure the convergence and quit learning early. You can use stochastic gradient following as an online learning method since you update the model for every new datapoint, as I think you yourself said. Although, I'd be careful about calling it "per training data." Training data is a dataset, not a datapoint, but I think I understood you since you said "per training data."
What is the difference between online and batch Learning? [duplicate]
To me it looks like they are using batch and online learning correctly. In section 3 they are working on the whole dataset to perform learning, i.e., batch learning, while in section 4 they switch to
What is the difference between online and batch Learning? [duplicate] To me it looks like they are using batch and online learning correctly. In section 3 they are working on the whole dataset to perform learning, i.e., batch learning, while in section 4 they switch to stochastic gradient following which can be used as an online learning algorithm. I've never used stochastic gradient following as an online learning algorithm; however, it is possible to simply stop the optimization process in the middle of a learning run and it still being a useful model. For very big datasets this is useful since you can measure the convergence and quit learning early. You can use stochastic gradient following as an online learning method since you update the model for every new datapoint, as I think you yourself said. Although, I'd be careful about calling it "per training data." Training data is a dataset, not a datapoint, but I think I understood you since you said "per training data."
What is the difference between online and batch Learning? [duplicate] To me it looks like they are using batch and online learning correctly. In section 3 they are working on the whole dataset to perform learning, i.e., batch learning, while in section 4 they switch to
13,067
What is the difference between online and batch Learning? [duplicate]
In short, Online: Learning based on each pattern as it is observed. Batch: Learning over groups of patters. Most algorithms are batch. Source: http://machinelearningmastery.com/basic-concepts-in-machine-learning/
What is the difference between online and batch Learning? [duplicate]
In short, Online: Learning based on each pattern as it is observed. Batch: Learning over groups of patters. Most algorithms are batch. Source: http://machinelearningmastery.com/basic-concepts-in-machi
What is the difference between online and batch Learning? [duplicate] In short, Online: Learning based on each pattern as it is observed. Batch: Learning over groups of patters. Most algorithms are batch. Source: http://machinelearningmastery.com/basic-concepts-in-machine-learning/
What is the difference between online and batch Learning? [duplicate] In short, Online: Learning based on each pattern as it is observed. Batch: Learning over groups of patters. Most algorithms are batch. Source: http://machinelearningmastery.com/basic-concepts-in-machi
13,068
What is the difference between online and batch Learning? [duplicate]
Batch Versus On-line Learning The on-line and batch modes are slightly different, although both will perform well for parabolic performance surfaces. One major difference is that the batch algorithm keeps the system weights constant while computing the error associated with each sample in the input. Since the on-line version is constantly updating its weights, its error calculation (and thus gradient estimation) uses different weights for each input sample. This means that the two algorithms visit different sets of points during adaptation. However, they both converge to the same minimum. Note that the number of weight updates of the two methods for the same number of data presentations is very different. The on-line method (LMS) does an update each sample, while batch does an update each epoch, that is, LMS updates = (batch updates) x (# of samples in training set). The batch algorithm is also slightly more efficient in terms of number of computations.
What is the difference between online and batch Learning? [duplicate]
Batch Versus On-line Learning The on-line and batch modes are slightly different, although both will perform well for parabolic performance surfaces. One major difference is that the batch algorithm k
What is the difference between online and batch Learning? [duplicate] Batch Versus On-line Learning The on-line and batch modes are slightly different, although both will perform well for parabolic performance surfaces. One major difference is that the batch algorithm keeps the system weights constant while computing the error associated with each sample in the input. Since the on-line version is constantly updating its weights, its error calculation (and thus gradient estimation) uses different weights for each input sample. This means that the two algorithms visit different sets of points during adaptation. However, they both converge to the same minimum. Note that the number of weight updates of the two methods for the same number of data presentations is very different. The on-line method (LMS) does an update each sample, while batch does an update each epoch, that is, LMS updates = (batch updates) x (# of samples in training set). The batch algorithm is also slightly more efficient in terms of number of computations.
What is the difference between online and batch Learning? [duplicate] Batch Versus On-line Learning The on-line and batch modes are slightly different, although both will perform well for parabolic performance surfaces. One major difference is that the batch algorithm k
13,069
How to use DLM with Kalman filtering for forecasting
The paper at JSS 39-02 compares 5 different Kalman filtering R packages and gives sample code.
How to use DLM with Kalman filtering for forecasting
The paper at JSS 39-02 compares 5 different Kalman filtering R packages and gives sample code.
How to use DLM with Kalman filtering for forecasting The paper at JSS 39-02 compares 5 different Kalman filtering R packages and gives sample code.
How to use DLM with Kalman filtering for forecasting The paper at JSS 39-02 compares 5 different Kalman filtering R packages and gives sample code.
13,070
How to use DLM with Kalman filtering for forecasting
DLMs are cool, but they are not as simple as, say, ARIMA or other methods. In other methods, you plug in your data and then tweak some parameters of the algorithm, perhaps referring to various diagnostics to guide your settings. With a DLM, you are creating a state space machine, which consists of several matrices that basically implement something like a Hidden Markov Model. Some packages (sspir I think, among others) expect that you understand the concept and what the matrices do. I'd highly recommend that you start with the dlm package, and as @RockScience recommends, walk through the vignette. With dlm you're going to basically take several steps: What kinds of components describe my series? A trend? Seasonality? Exogenous variables? You will use dlm tools like dlmModPoly to implement these components, using the + operator to join them together into one model. Create an R subroutine that takes however many parameters are required by this model, creates the components with those parameters, then adds them together and returns the resulting model. Use dlmMLE to do an search/optimization to find the appropriate parameters (using MLE, which is basically optimization, with the pitfalls that can occur in optimization). dlmMLE repeatedly calls your R subroutine with candidate parameters to create models, then tests them. Create your final model, using the R subroutine you created plus the parameters you found in step 3. Filter your data with dlmFilter, then perhaps smooth with dlmSmooth. If you use dlmModReg or do anything that causes the model to have time-variant parameters, you can't use dlmForecast to forecast your series. If you do end up with a time-variant model, you'll want to fill out your input data with NA's and let the dlmFilter fill in the NA's for you (a poor man's forecast), since dlmForecast does not work with time-varying parameters. If you want to examine the components individually (say the trend, separately from the seasonal), you'll need to understand the matrices and what's in each column, plus understand a bit of how dlm puts them together (order matters!). There's another package, whose name escapes me, which tries to create a front end that can use several of these packages (including dlm as the back end). Unfortunately, I've never gotten it to work well, but that might just be me. I'd really recommend getting a book on DLMs. I got a couple of them and played a lot with dlm to get to where I am, and I'm not the expert by any means.
How to use DLM with Kalman filtering for forecasting
DLMs are cool, but they are not as simple as, say, ARIMA or other methods. In other methods, you plug in your data and then tweak some parameters of the algorithm, perhaps referring to various diagnos
How to use DLM with Kalman filtering for forecasting DLMs are cool, but they are not as simple as, say, ARIMA or other methods. In other methods, you plug in your data and then tweak some parameters of the algorithm, perhaps referring to various diagnostics to guide your settings. With a DLM, you are creating a state space machine, which consists of several matrices that basically implement something like a Hidden Markov Model. Some packages (sspir I think, among others) expect that you understand the concept and what the matrices do. I'd highly recommend that you start with the dlm package, and as @RockScience recommends, walk through the vignette. With dlm you're going to basically take several steps: What kinds of components describe my series? A trend? Seasonality? Exogenous variables? You will use dlm tools like dlmModPoly to implement these components, using the + operator to join them together into one model. Create an R subroutine that takes however many parameters are required by this model, creates the components with those parameters, then adds them together and returns the resulting model. Use dlmMLE to do an search/optimization to find the appropriate parameters (using MLE, which is basically optimization, with the pitfalls that can occur in optimization). dlmMLE repeatedly calls your R subroutine with candidate parameters to create models, then tests them. Create your final model, using the R subroutine you created plus the parameters you found in step 3. Filter your data with dlmFilter, then perhaps smooth with dlmSmooth. If you use dlmModReg or do anything that causes the model to have time-variant parameters, you can't use dlmForecast to forecast your series. If you do end up with a time-variant model, you'll want to fill out your input data with NA's and let the dlmFilter fill in the NA's for you (a poor man's forecast), since dlmForecast does not work with time-varying parameters. If you want to examine the components individually (say the trend, separately from the seasonal), you'll need to understand the matrices and what's in each column, plus understand a bit of how dlm puts them together (order matters!). There's another package, whose name escapes me, which tries to create a front end that can use several of these packages (including dlm as the back end). Unfortunately, I've never gotten it to work well, but that might just be me. I'd really recommend getting a book on DLMs. I got a couple of them and played a lot with dlm to get to where I am, and I'm not the expert by any means.
How to use DLM with Kalman filtering for forecasting DLMs are cool, but they are not as simple as, say, ARIMA or other methods. In other methods, you plug in your data and then tweak some parameters of the algorithm, perhaps referring to various diagnos
13,071
How to use DLM with Kalman filtering for forecasting
I suggest you read the dlm vignette http://cran.r-project.org/web/packages/dlm/vignettes/dlm.pdf especially the chapter 3.3
How to use DLM with Kalman filtering for forecasting
I suggest you read the dlm vignette http://cran.r-project.org/web/packages/dlm/vignettes/dlm.pdf especially the chapter 3.3
How to use DLM with Kalman filtering for forecasting I suggest you read the dlm vignette http://cran.r-project.org/web/packages/dlm/vignettes/dlm.pdf especially the chapter 3.3
How to use DLM with Kalman filtering for forecasting I suggest you read the dlm vignette http://cran.r-project.org/web/packages/dlm/vignettes/dlm.pdf especially the chapter 3.3
13,072
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
Contrary to various unproven claims, cosine cannot be significantly better. It is easy to see that Cosine is essentially the same as Euclidean on normalized data. The normalization takes away one degree of freedom. Thus, cosine on a 1000 dimensional space is about as "cursed" as Euclidean on a 999 dimensional space. What is usually different is the data where you would use one vs. the other. Euclidean is commonly used on dense, continuous variables. There every dimension matters, and a 20 dimensional space can be challenging. Cosine is mostly used on very sparse, discrete domains such as text. Here, most dimensions are 0 and do not matter at all. A 100.000 dimensional vector space may have just some 50 nonzero dimensions for a distance computation; and of these many will have a low weight (stopwords). So it is the typical use case of cosine that is not cursed, even though it theoretically is a very high dimensional space. There is a term for this: intrinsic dimensionality vs. representation dimensionality.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
Contrary to various unproven claims, cosine cannot be significantly better. It is easy to see that Cosine is essentially the same as Euclidean on normalized data. The normalization takes away one degr
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] Contrary to various unproven claims, cosine cannot be significantly better. It is easy to see that Cosine is essentially the same as Euclidean on normalized data. The normalization takes away one degree of freedom. Thus, cosine on a 1000 dimensional space is about as "cursed" as Euclidean on a 999 dimensional space. What is usually different is the data where you would use one vs. the other. Euclidean is commonly used on dense, continuous variables. There every dimension matters, and a 20 dimensional space can be challenging. Cosine is mostly used on very sparse, discrete domains such as text. Here, most dimensions are 0 and do not matter at all. A 100.000 dimensional vector space may have just some 50 nonzero dimensions for a distance computation; and of these many will have a low weight (stopwords). So it is the typical use case of cosine that is not cursed, even though it theoretically is a very high dimensional space. There is a term for this: intrinsic dimensionality vs. representation dimensionality.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] Contrary to various unproven claims, cosine cannot be significantly better. It is easy to see that Cosine is essentially the same as Euclidean on normalized data. The normalization takes away one degr
13,073
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
However, I have read that using different distance metrics, such as a cosine similarity, performs better with high dimensional data. Most likely depends on context. The cosine distance is not impervious to the curse of dimensionality - in high dimensions two randomly picked vectors will be almost orthogonal with high probability, see 0.2 Funny facts from these notes.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
However, I have read that using different distance metrics, such as a cosine similarity, performs better with high dimensional data. Most likely depends on context. The cosine distance is not imper
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] However, I have read that using different distance metrics, such as a cosine similarity, performs better with high dimensional data. Most likely depends on context. The cosine distance is not impervious to the curse of dimensionality - in high dimensions two randomly picked vectors will be almost orthogonal with high probability, see 0.2 Funny facts from these notes.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] However, I have read that using different distance metrics, such as a cosine similarity, performs better with high dimensional data. Most likely depends on context. The cosine distance is not imper
13,074
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
Cosine similarity is correlation, which is greater for objects with similar angles from, say, the origin (0,0,0,0,....) over the feature values. So correlation is a similarity index. Euclidean distance is lowest between objects with the same distance and angle from the origin. So, two objects with the same angle (corr) can have a far distance (Euclidean) from one another. I wouldn't say that Euclidean distance is useless for anything. Correlation will identify objects with similar feature values but with additive or multiplicative translations between the objects. For example, two objects $\textbf{x}_i=(1,2,3,4)$ and $\textbf{x}_j=(1,4,6,8)$ which are a multiplicative constant of 2 away from each other will have perfect correlation (unity). Also, two objects $\textbf{x}_i=(1,2,3,4)$ and $\textbf{x}_j=(1.25,2.25,3.25,4.25)$ which are an additive constant of 0.25 away from each other will have perfect correlation (unity). However, Euclidean distance, $d(\textbf{x}_i, \textbf{x}_j)>0$ -- will be greater than zero. The problem you are looking for is called the "overlap problem", where in the above two examples of perfect correlation, objects can be perfectly correlated but with different distances. In hierarchical cluster analysis, if you want agglomeration of objects with almost the same levels of features values (i.e, almost the same objects), you would use Euclidean distance. However, if you want to agglomerate together objects with similar patterns that may vary by constant additive or multiplicative translation, then you would use correlation, or 1 minus correlation, which makes correlation look like a distance with range [0,2]. In biology for example, you want to preferably use correlation to identify genes which may be co-regulated or associated (correlated), whose expression patterns correlate together ("co-vary" --> covariance) over the objects. In this case, however, using Euclidean distance would only identify genes with the same level of expression, which won't mean much when trying to find co-regulatory genes. Euclidean distance is best for finding like objects with feature values that are low or high together. FYI-curse of dimensionality is commonly a problem that creates the "small sample problem" $(p>>n)$, when there are too many features compared to the number of objects. It doesn't have anything to do with distance metrics, since you can always mean-zero standardize, normalize, use percentiles, or fuzzify feature values to get away from issues of scale.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate]
Cosine similarity is correlation, which is greater for objects with similar angles from, say, the origin (0,0,0,0,....) over the feature values. So correlation is a similarity index. Euclidean dista
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] Cosine similarity is correlation, which is greater for objects with similar angles from, say, the origin (0,0,0,0,....) over the feature values. So correlation is a similarity index. Euclidean distance is lowest between objects with the same distance and angle from the origin. So, two objects with the same angle (corr) can have a far distance (Euclidean) from one another. I wouldn't say that Euclidean distance is useless for anything. Correlation will identify objects with similar feature values but with additive or multiplicative translations between the objects. For example, two objects $\textbf{x}_i=(1,2,3,4)$ and $\textbf{x}_j=(1,4,6,8)$ which are a multiplicative constant of 2 away from each other will have perfect correlation (unity). Also, two objects $\textbf{x}_i=(1,2,3,4)$ and $\textbf{x}_j=(1.25,2.25,3.25,4.25)$ which are an additive constant of 0.25 away from each other will have perfect correlation (unity). However, Euclidean distance, $d(\textbf{x}_i, \textbf{x}_j)>0$ -- will be greater than zero. The problem you are looking for is called the "overlap problem", where in the above two examples of perfect correlation, objects can be perfectly correlated but with different distances. In hierarchical cluster analysis, if you want agglomeration of objects with almost the same levels of features values (i.e, almost the same objects), you would use Euclidean distance. However, if you want to agglomerate together objects with similar patterns that may vary by constant additive or multiplicative translation, then you would use correlation, or 1 minus correlation, which makes correlation look like a distance with range [0,2]. In biology for example, you want to preferably use correlation to identify genes which may be co-regulated or associated (correlated), whose expression patterns correlate together ("co-vary" --> covariance) over the objects. In this case, however, using Euclidean distance would only identify genes with the same level of expression, which won't mean much when trying to find co-regulatory genes. Euclidean distance is best for finding like objects with feature values that are low or high together. FYI-curse of dimensionality is commonly a problem that creates the "small sample problem" $(p>>n)$, when there are too many features compared to the number of objects. It doesn't have anything to do with distance metrics, since you can always mean-zero standardize, normalize, use percentiles, or fuzzify feature values to get away from issues of scale.
Curse of dimensionality- does cosine similarity work better and if so, why? [duplicate] Cosine similarity is correlation, which is greater for objects with similar angles from, say, the origin (0,0,0,0,....) over the feature values. So correlation is a similarity index. Euclidean dista
13,075
Is it okay to use cross entropy loss function with soft labels?
The answer is yes, but you have to define it the right way. Cross entropy is defined on probability distributions, not on single values. For discrete distributions $p$ and $q$, it's: $$H(p, q) = -\sum_y p(y) \log q(y)$$ When the cross entropy loss is used with 'hard' class labels, what this really amounts to is treating $p$ as the conditional empirical distribution over class labels. This is a distribution where the probability is 1 for the observed class label and 0 for all others. $q$ is the conditional distribution (probability of class label, given input) learned by the classifier. For a single observed data point with input $x_0$ and class $y_0$, we can see that the expression above reduces to the standard log loss (which would be averaged over all data points): $$-\sum_y I\{y = y_0\} \log q(y \mid x_0) = -\log q(y_0 \mid x_0)$$ Here, $I\{\cdot\}$ is the indicator function, which is 1 when its argument is true or 0 otherwise (this is what the empirical distribution is doing). The sum is taken over the set of possible class labels. In the case of 'soft' labels like you mention, the labels are no longer class identities themselves, but probabilities over two possible classes. Because of this, you can't use the standard expression for the log loss. But, the concept of cross entropy still applies. In fact, it seems even more natural in this case. Let's call the class $y$, which can be 0 or 1. And, let's say that the soft label $s(x)$ gives the probability that the class is 1 (given the corresponding input $x$). So, the soft label defines a probability distribution: $$p(y \mid x) = \left \{ \begin{array}{cl} s(x) & \text{If } y = 1 \\ 1-s(x) & \text{If } y = 0 \end{array} \right .$$ The classifier also gives a distribution over classes, given the input: $$ q(y \mid x) = \left \{ \begin{array}{cl} c(x) & \text{If } y = 1 \\ 1-c(x) & \text{If } y = 0 \end{array} \right . $$ Here, $c(x)$ is the classifier's estimated probability that the class is 1, given input $x$. The task is now to determine how different these two distributions are, using the cross entropy. Plug these expressions for $p$ and $q$ into the definition of cross entropy, above. The sum is taken over the set of possible classes $\{0, 1\}$: $$ \begin{array}{ccl} H(p, q) & = & - p(y=0 \mid x) \log q(y=0 \mid x) - p(y=1 \mid x) \log q(y=1 \mid x)\\ & = & -(1-s(x)) \log (1-c(x)) - s(x) \log c(x) \end{array} $$ That's the expression for a single, observed data point. The loss function would be the mean over all data points. Of course, this can be generalized to multiclass classification as well.
Is it okay to use cross entropy loss function with soft labels?
The answer is yes, but you have to define it the right way. Cross entropy is defined on probability distributions, not on single values. For discrete distributions $p$ and $q$, it's: $$H(p, q) = -\sum
Is it okay to use cross entropy loss function with soft labels? The answer is yes, but you have to define it the right way. Cross entropy is defined on probability distributions, not on single values. For discrete distributions $p$ and $q$, it's: $$H(p, q) = -\sum_y p(y) \log q(y)$$ When the cross entropy loss is used with 'hard' class labels, what this really amounts to is treating $p$ as the conditional empirical distribution over class labels. This is a distribution where the probability is 1 for the observed class label and 0 for all others. $q$ is the conditional distribution (probability of class label, given input) learned by the classifier. For a single observed data point with input $x_0$ and class $y_0$, we can see that the expression above reduces to the standard log loss (which would be averaged over all data points): $$-\sum_y I\{y = y_0\} \log q(y \mid x_0) = -\log q(y_0 \mid x_0)$$ Here, $I\{\cdot\}$ is the indicator function, which is 1 when its argument is true or 0 otherwise (this is what the empirical distribution is doing). The sum is taken over the set of possible class labels. In the case of 'soft' labels like you mention, the labels are no longer class identities themselves, but probabilities over two possible classes. Because of this, you can't use the standard expression for the log loss. But, the concept of cross entropy still applies. In fact, it seems even more natural in this case. Let's call the class $y$, which can be 0 or 1. And, let's say that the soft label $s(x)$ gives the probability that the class is 1 (given the corresponding input $x$). So, the soft label defines a probability distribution: $$p(y \mid x) = \left \{ \begin{array}{cl} s(x) & \text{If } y = 1 \\ 1-s(x) & \text{If } y = 0 \end{array} \right .$$ The classifier also gives a distribution over classes, given the input: $$ q(y \mid x) = \left \{ \begin{array}{cl} c(x) & \text{If } y = 1 \\ 1-c(x) & \text{If } y = 0 \end{array} \right . $$ Here, $c(x)$ is the classifier's estimated probability that the class is 1, given input $x$. The task is now to determine how different these two distributions are, using the cross entropy. Plug these expressions for $p$ and $q$ into the definition of cross entropy, above. The sum is taken over the set of possible classes $\{0, 1\}$: $$ \begin{array}{ccl} H(p, q) & = & - p(y=0 \mid x) \log q(y=0 \mid x) - p(y=1 \mid x) \log q(y=1 \mid x)\\ & = & -(1-s(x)) \log (1-c(x)) - s(x) \log c(x) \end{array} $$ That's the expression for a single, observed data point. The loss function would be the mean over all data points. Of course, this can be generalized to multiclass classification as well.
Is it okay to use cross entropy loss function with soft labels? The answer is yes, but you have to define it the right way. Cross entropy is defined on probability distributions, not on single values. For discrete distributions $p$ and $q$, it's: $$H(p, q) = -\sum
13,076
What is simply meant by reduced form?
To complement Dimitriy's answer (+1), the structural form and the reduced form are two ways of thinking about your system of equations. The structural form is what your economic theory says the economic relations between the variables are (like consumption and income in the linked Keynesian example). However, getting the estimates of the model coefficients requires jumping through multiple hoops to make sure these estimates are not biased because of endogeneity problems when one endogenous variable is regressed on another. So structural form is good for intuitive explanation, and terrible to work with when the numbers come in. The reduced form complements the structural form in functionality. As Dimitriy said, and as shown in the consumption example, the reduced form solves for the endogenous variables (if at all possible) -- this is American Algebra II material, to my knowledge. In the end, in each equation, one and only one endogenous variable appears in the left hand side, and the right hand side only contains exogenous variables and error terms. If at all possible is an important qualifier: sometimes it will not be possible to arrive at such a transformation of the structural form, and it means that the model is not identified, and no amount of data will help you get estimates of your parameters. The reduced form is easily estimable though, as you can run something as basic as OLS on each equation to get some estimates (although these won't be the best possible estimates), and they will be unbiased for the reduced form parameters. However, there may or may not be a nice cross-walk back to the structural form, which had interpretable parameters. Thus the reduced form is good for estimation, but terrible for interpretation. Reduced form can also be used for prediction, including impulse response functions -- this may have been the reason somebody wanted to see these estimates.
What is simply meant by reduced form?
To complement Dimitriy's answer (+1), the structural form and the reduced form are two ways of thinking about your system of equations. The structural form is what your economic theory says the econom
What is simply meant by reduced form? To complement Dimitriy's answer (+1), the structural form and the reduced form are two ways of thinking about your system of equations. The structural form is what your economic theory says the economic relations between the variables are (like consumption and income in the linked Keynesian example). However, getting the estimates of the model coefficients requires jumping through multiple hoops to make sure these estimates are not biased because of endogeneity problems when one endogenous variable is regressed on another. So structural form is good for intuitive explanation, and terrible to work with when the numbers come in. The reduced form complements the structural form in functionality. As Dimitriy said, and as shown in the consumption example, the reduced form solves for the endogenous variables (if at all possible) -- this is American Algebra II material, to my knowledge. In the end, in each equation, one and only one endogenous variable appears in the left hand side, and the right hand side only contains exogenous variables and error terms. If at all possible is an important qualifier: sometimes it will not be possible to arrive at such a transformation of the structural form, and it means that the model is not identified, and no amount of data will help you get estimates of your parameters. The reduced form is easily estimable though, as you can run something as basic as OLS on each equation to get some estimates (although these won't be the best possible estimates), and they will be unbiased for the reduced form parameters. However, there may or may not be a nice cross-walk back to the structural form, which had interpretable parameters. Thus the reduced form is good for estimation, but terrible for interpretation. Reduced form can also be used for prediction, including impulse response functions -- this may have been the reason somebody wanted to see these estimates.
What is simply meant by reduced form? To complement Dimitriy's answer (+1), the structural form and the reduced form are two ways of thinking about your system of equations. The structural form is what your economic theory says the econom
13,077
What is simply meant by reduced form?
Take a look at this simple example showing how the Keynesian consumption function and equilibrium condition can be re-written in a reduced form. The reduced form of a model is the one in which the endogenous variables are expressed as functions of the exogenous variables (and perhaps lagged values of the endogenous variables). Very roughly, reduced form estimates do not give you the structural, primitive policy-invariant behavioral parameters that you (sometimes) care about, such as parameters of an agent's utility function or the slopes of the demand and supply curves. With RFEs, you only get functions of those parameters (and often not even that). For some purposes, that can be enough, which is why some people want to see them. For example, you can frequently get the sign of the relationship from RF estimates, but not the magnitude. Once is a blue moon, you can use algebra to solve for structural parameters from the RFEs. Finally, it is also the case that some people will not believe the assumptions needed to estimate the structural parameters.
What is simply meant by reduced form?
Take a look at this simple example showing how the Keynesian consumption function and equilibrium condition can be re-written in a reduced form. The reduced form of a model is the one in which the end
What is simply meant by reduced form? Take a look at this simple example showing how the Keynesian consumption function and equilibrium condition can be re-written in a reduced form. The reduced form of a model is the one in which the endogenous variables are expressed as functions of the exogenous variables (and perhaps lagged values of the endogenous variables). Very roughly, reduced form estimates do not give you the structural, primitive policy-invariant behavioral parameters that you (sometimes) care about, such as parameters of an agent's utility function or the slopes of the demand and supply curves. With RFEs, you only get functions of those parameters (and often not even that). For some purposes, that can be enough, which is why some people want to see them. For example, you can frequently get the sign of the relationship from RF estimates, but not the magnitude. Once is a blue moon, you can use algebra to solve for structural parameters from the RFEs. Finally, it is also the case that some people will not believe the assumptions needed to estimate the structural parameters.
What is simply meant by reduced form? Take a look at this simple example showing how the Keynesian consumption function and equilibrium condition can be re-written in a reduced form. The reduced form of a model is the one in which the end
13,078
What is simply meant by reduced form?
When you do a regression involving two steps (two-step least squares, or 2sls) you have two equations. The first equations, named the structural equation, looks like any other regression equation. The second equation is the reduced form equation (and looks a lot like any other regression equation). The reason for doing a 2sls is that some variable in the first equation correlated with the error term, which violates the basic assumptions of regression analysis. To fix this problem you make the second equation (the reduced form equation) using the correlated variable as the dependent variable and a set of independent variables (which in this case get the fancy name of instrumental variables) that you think will correct the correlation problem along with all the independent variables from the first equation. Then you have the computer run it. The output will provide you the estimates you need. So in short, I think the person asking for your reduced form estimates, wants to see your work. Particularly they want to see the second equations and the associated betas --- show them the regression output and they should be happy. Hope this helps!
What is simply meant by reduced form?
When you do a regression involving two steps (two-step least squares, or 2sls) you have two equations. The first equations, named the structural equation, looks like any other regression equation.
What is simply meant by reduced form? When you do a regression involving two steps (two-step least squares, or 2sls) you have two equations. The first equations, named the structural equation, looks like any other regression equation. The second equation is the reduced form equation (and looks a lot like any other regression equation). The reason for doing a 2sls is that some variable in the first equation correlated with the error term, which violates the basic assumptions of regression analysis. To fix this problem you make the second equation (the reduced form equation) using the correlated variable as the dependent variable and a set of independent variables (which in this case get the fancy name of instrumental variables) that you think will correct the correlation problem along with all the independent variables from the first equation. Then you have the computer run it. The output will provide you the estimates you need. So in short, I think the person asking for your reduced form estimates, wants to see your work. Particularly they want to see the second equations and the associated betas --- show them the regression output and they should be happy. Hope this helps!
What is simply meant by reduced form? When you do a regression involving two steps (two-step least squares, or 2sls) you have two equations. The first equations, named the structural equation, looks like any other regression equation.
13,079
What is simply meant by reduced form?
Jörn-Steffen Pischke provides a very pragmatic explanation of the reduced form in the context of instrumental variables analysis (IV) in his lecture notes. He essentially distinguishes 3 causal effects of interest: the causal effect of the instrument (Z) on the endogenous variable (X) - obtained in the first stage; the causal effect of the instrument (Z) on the outcome of interest (Y) - obtained in the reduced form; the causal effect of the endogenous variable (X) on the outcome of interest (Y) - obtained in the second stage. Although what we ultimately care about (after all it's the whole reason why we do this IV exercise) is causal effect number 3, and we can obtain this also without estimating causal effect number 2, Pischke argues that this parameter might be interesting in it's own right: "For example, the instrument might be a policy variable in which case it is the policy effect." Another source of interest might be the lecture notes by Kurt Schmidheiny. He mentions the reduced form in the context of weak instruments (F-stat of 1st stage < 10). In such case hypothesis testing based on the IV estimates is no longer valid. A 'reduced form test' might provide an alternative. In his words: "Reduced form estimation offers a simple approach to test the null hypothesis H0 that all K coefficients βk related to the endogenous explanatory variables [...] are simultaneously equal to zero." This essentially means that one can use the reduced form to assess whether the instruments have a direct effect on the outcome of interest. Under H0 they do not have an effect (are not significantly different from zero).
What is simply meant by reduced form?
Jörn-Steffen Pischke provides a very pragmatic explanation of the reduced form in the context of instrumental variables analysis (IV) in his lecture notes. He essentially distinguishes 3 causal effect
What is simply meant by reduced form? Jörn-Steffen Pischke provides a very pragmatic explanation of the reduced form in the context of instrumental variables analysis (IV) in his lecture notes. He essentially distinguishes 3 causal effects of interest: the causal effect of the instrument (Z) on the endogenous variable (X) - obtained in the first stage; the causal effect of the instrument (Z) on the outcome of interest (Y) - obtained in the reduced form; the causal effect of the endogenous variable (X) on the outcome of interest (Y) - obtained in the second stage. Although what we ultimately care about (after all it's the whole reason why we do this IV exercise) is causal effect number 3, and we can obtain this also without estimating causal effect number 2, Pischke argues that this parameter might be interesting in it's own right: "For example, the instrument might be a policy variable in which case it is the policy effect." Another source of interest might be the lecture notes by Kurt Schmidheiny. He mentions the reduced form in the context of weak instruments (F-stat of 1st stage < 10). In such case hypothesis testing based on the IV estimates is no longer valid. A 'reduced form test' might provide an alternative. In his words: "Reduced form estimation offers a simple approach to test the null hypothesis H0 that all K coefficients βk related to the endogenous explanatory variables [...] are simultaneously equal to zero." This essentially means that one can use the reduced form to assess whether the instruments have a direct effect on the outcome of interest. Under H0 they do not have an effect (are not significantly different from zero).
What is simply meant by reduced form? Jörn-Steffen Pischke provides a very pragmatic explanation of the reduced form in the context of instrumental variables analysis (IV) in his lecture notes. He essentially distinguishes 3 causal effect
13,080
What is simply meant by reduced form?
Agree with @user107905, if you use the 2SLS the reduced format equation is used to construct the IV, while the original structural equation can still be fitted through OLS by plugging in the fitted endogenous value. In that way, you can still get INTERPRETABLE parameters for the original/1st structural equation. see chapter 15 Instrumental variables estimation and two stage least squares in 'Introductory Econometrics A Modern Approach' Wooldridge.
What is simply meant by reduced form?
Agree with @user107905, if you use the 2SLS the reduced format equation is used to construct the IV, while the original structural equation can still be fitted through OLS by plugging in the fitted en
What is simply meant by reduced form? Agree with @user107905, if you use the 2SLS the reduced format equation is used to construct the IV, while the original structural equation can still be fitted through OLS by plugging in the fitted endogenous value. In that way, you can still get INTERPRETABLE parameters for the original/1st structural equation. see chapter 15 Instrumental variables estimation and two stage least squares in 'Introductory Econometrics A Modern Approach' Wooldridge.
What is simply meant by reduced form? Agree with @user107905, if you use the 2SLS the reduced format equation is used to construct the IV, while the original structural equation can still be fitted through OLS by plugging in the fitted en
13,081
Intercept term in logistic regression
$\beta_0$ is not the odds of the event when $x_1 = x_2 = 0$, it is the log of the odds. In addition, it is the log odds only when $x_1 = x_2 = 0$, not when they are at their lowest non-zero values.
Intercept term in logistic regression
$\beta_0$ is not the odds of the event when $x_1 = x_2 = 0$, it is the log of the odds. In addition, it is the log odds only when $x_1 = x_2 = 0$, not when they are at their lowest non-zero values.
Intercept term in logistic regression $\beta_0$ is not the odds of the event when $x_1 = x_2 = 0$, it is the log of the odds. In addition, it is the log odds only when $x_1 = x_2 = 0$, not when they are at their lowest non-zero values.
Intercept term in logistic regression $\beta_0$ is not the odds of the event when $x_1 = x_2 = 0$, it is the log of the odds. In addition, it is the log odds only when $x_1 = x_2 = 0$, not when they are at their lowest non-zero values.
13,082
Intercept term in logistic regression
There also might be a case when $x_1$ and $x_2$ can not be equal to $0$ at the same time. In this case $\beta_0$ does not have clear interpretation. Otherwise $\beta_0$ has an interpretation - it shifts the log of the odds to its factual value, if no one variable can not do this.
Intercept term in logistic regression
There also might be a case when $x_1$ and $x_2$ can not be equal to $0$ at the same time. In this case $\beta_0$ does not have clear interpretation. Otherwise $\beta_0$ has an interpretation - it shi
Intercept term in logistic regression There also might be a case when $x_1$ and $x_2$ can not be equal to $0$ at the same time. In this case $\beta_0$ does not have clear interpretation. Otherwise $\beta_0$ has an interpretation - it shifts the log of the odds to its factual value, if no one variable can not do this.
Intercept term in logistic regression There also might be a case when $x_1$ and $x_2$ can not be equal to $0$ at the same time. In this case $\beta_0$ does not have clear interpretation. Otherwise $\beta_0$ has an interpretation - it shi
13,083
Intercept term in logistic regression
I suggest to look at it a different way ... In logistic regression we predict some binary class {0 or 1} by calculating the probability of likelihood, which is the actual output of $\text{logit}(p)$. This, of course, is assuming that the log-odds can reasonably be described by a linear function -- e.g., $\beta_0 + \beta_1x_1 + \beta_2x_2+ \dotsm $ ... This is a big assumption, and only sometimes holds true. If those $x_i$ components don't have independent, proportional influence on the log-odds, then best to choose another statistical framework. I.e., the log-odds is made up of some fixed component $\beta_0$, and increased incrementally by each successive term, $\beta_i x_i$. In short, the $\beta_0$ value is the "fixed component" of that component-wise method to describe the log-odds of whatever event/condition you are trying to predict. Also remember that a regression is ultimately describing some conditional average, given a set of $x_i$ values. None of those things require that $x_i$-values be 0 in your data or even possible in reality. The $\beta_0$ simply shifts that linear expression up or down so that the variable components are most accurate. Maybe I said the same thing in slightly different mindset, but I hope this helps ...
Intercept term in logistic regression
I suggest to look at it a different way ... In logistic regression we predict some binary class {0 or 1} by calculating the probability of likelihood, which is the actual output of $\text{logit}(p)$.
Intercept term in logistic regression I suggest to look at it a different way ... In logistic regression we predict some binary class {0 or 1} by calculating the probability of likelihood, which is the actual output of $\text{logit}(p)$. This, of course, is assuming that the log-odds can reasonably be described by a linear function -- e.g., $\beta_0 + \beta_1x_1 + \beta_2x_2+ \dotsm $ ... This is a big assumption, and only sometimes holds true. If those $x_i$ components don't have independent, proportional influence on the log-odds, then best to choose another statistical framework. I.e., the log-odds is made up of some fixed component $\beta_0$, and increased incrementally by each successive term, $\beta_i x_i$. In short, the $\beta_0$ value is the "fixed component" of that component-wise method to describe the log-odds of whatever event/condition you are trying to predict. Also remember that a regression is ultimately describing some conditional average, given a set of $x_i$ values. None of those things require that $x_i$-values be 0 in your data or even possible in reality. The $\beta_0$ simply shifts that linear expression up or down so that the variable components are most accurate. Maybe I said the same thing in slightly different mindset, but I hope this helps ...
Intercept term in logistic regression I suggest to look at it a different way ... In logistic regression we predict some binary class {0 or 1} by calculating the probability of likelihood, which is the actual output of $\text{logit}(p)$.
13,084
Transformation to increase kurtosis and skewness of normal r.v
This can be done using the sinh-arcsinh transformation from Jones, M. C. and Pewsey A. (2009). Sinh-arcsinh distributions. Biometrika 96: 761–780. The transformation is defined as $$H(x;\epsilon,\delta)=\sinh[\delta\sinh^{-1}(x)-\epsilon], \tag{$\star$}$$ where $\epsilon \in{\mathbb R}$ and $\delta \in {\mathbb R}_+$. When this transformation is applied to the normal CDF $S(x;\epsilon,\delta)=\Phi[H(x;\epsilon,\delta)]$, it produces a unimodal distribution whose parameters $(\epsilon,\delta)$ control skewness and kurtosis, respectively (Jones and Pewsey, 2009), in the sense of van Zwet (1969). In addition, if $\epsilon=0$ and $\delta=1$, we obtain the original normal distribution. See the following R code. fs = function(x,epsilon,delta) dnorm(sinh(delta*asinh(x)-epsilon))*delta*cosh(delta*asinh(x)-epsilon)/sqrt(1+x^2) vec = seq(-15,15,0.001) plot(vec,fs(vec,0,1),type="l") points(vec,fs(vec,1,1),type="l",col="red") points(vec,fs(vec,2,1),type="l",col="blue") points(vec,fs(vec,-1,1),type="l",col="red") points(vec,fs(vec,-2,1),type="l",col="blue") vec = seq(-5,5,0.001) plot(vec,fs(vec,0,0.5),type="l",ylim=c(0,1)) points(vec,fs(vec,0,0.75),type="l",col="red") points(vec,fs(vec,0,1),type="l",col="blue") points(vec,fs(vec,0,1.25),type="l",col="red") points(vec,fs(vec,0,1.5),type="l",col="blue") Therefore, by choosing an appropriate sequence of parameters $(\epsilon_n,\delta_n)$, you can generate a sequence of distributions/transformations with different levels of skewness and kurtosis and make them look as similar or as different to the normal distribution as you want. The following plot shows the outcome produced by the R code. For (i) $\epsilon=(-2,-1,0,1,2)$ and $\delta=1$, and (ii) $\epsilon=0$ and $\delta=(0.5,0.75,1,1.25,1.5)$. Simulation of this distribution is straightforward given that you just have to transform a normal sample using the inverse of $(\star)$. $$H^{-1}(x;\epsilon,\delta)=\sinh[\delta^{-1}(\sinh^{-1}(x)+\epsilon)]$$
Transformation to increase kurtosis and skewness of normal r.v
This can be done using the sinh-arcsinh transformation from Jones, M. C. and Pewsey A. (2009). Sinh-arcsinh distributions. Biometrika 96: 761–780. The transformation is defined as $$H(x;\epsilon,\d
Transformation to increase kurtosis and skewness of normal r.v This can be done using the sinh-arcsinh transformation from Jones, M. C. and Pewsey A. (2009). Sinh-arcsinh distributions. Biometrika 96: 761–780. The transformation is defined as $$H(x;\epsilon,\delta)=\sinh[\delta\sinh^{-1}(x)-\epsilon], \tag{$\star$}$$ where $\epsilon \in{\mathbb R}$ and $\delta \in {\mathbb R}_+$. When this transformation is applied to the normal CDF $S(x;\epsilon,\delta)=\Phi[H(x;\epsilon,\delta)]$, it produces a unimodal distribution whose parameters $(\epsilon,\delta)$ control skewness and kurtosis, respectively (Jones and Pewsey, 2009), in the sense of van Zwet (1969). In addition, if $\epsilon=0$ and $\delta=1$, we obtain the original normal distribution. See the following R code. fs = function(x,epsilon,delta) dnorm(sinh(delta*asinh(x)-epsilon))*delta*cosh(delta*asinh(x)-epsilon)/sqrt(1+x^2) vec = seq(-15,15,0.001) plot(vec,fs(vec,0,1),type="l") points(vec,fs(vec,1,1),type="l",col="red") points(vec,fs(vec,2,1),type="l",col="blue") points(vec,fs(vec,-1,1),type="l",col="red") points(vec,fs(vec,-2,1),type="l",col="blue") vec = seq(-5,5,0.001) plot(vec,fs(vec,0,0.5),type="l",ylim=c(0,1)) points(vec,fs(vec,0,0.75),type="l",col="red") points(vec,fs(vec,0,1),type="l",col="blue") points(vec,fs(vec,0,1.25),type="l",col="red") points(vec,fs(vec,0,1.5),type="l",col="blue") Therefore, by choosing an appropriate sequence of parameters $(\epsilon_n,\delta_n)$, you can generate a sequence of distributions/transformations with different levels of skewness and kurtosis and make them look as similar or as different to the normal distribution as you want. The following plot shows the outcome produced by the R code. For (i) $\epsilon=(-2,-1,0,1,2)$ and $\delta=1$, and (ii) $\epsilon=0$ and $\delta=(0.5,0.75,1,1.25,1.5)$. Simulation of this distribution is straightforward given that you just have to transform a normal sample using the inverse of $(\star)$. $$H^{-1}(x;\epsilon,\delta)=\sinh[\delta^{-1}(\sinh^{-1}(x)+\epsilon)]$$
Transformation to increase kurtosis and skewness of normal r.v This can be done using the sinh-arcsinh transformation from Jones, M. C. and Pewsey A. (2009). Sinh-arcsinh distributions. Biometrika 96: 761–780. The transformation is defined as $$H(x;\epsilon,\d
13,085
Transformation to increase kurtosis and skewness of normal r.v
This can be done using Lambert W x F random variables / distributions. A Lambert W x F random variable (RV) is a non-linearly transformed (RV) X with distribution F. For F being the Normal distribution and $\alpha = 1$, they reduce to Tukey's h distribution. The nice property of Lambert W x F distributions is that you can also go back from non-normal to Normal again; i.e., you can estimate parameters and Gaussianize() your data. They are implemented in the Lambert W x F transformations come in 3 flavors: skewed (type = 's') with skewness parameter $\gamma \in R$ heavy-tailed (type = 'h') with tail parameter $\delta \geq 0$ (and optional $\alpha$) skewed and heavy tailed (type = 'hh') with left/right tail parameter $\delta_l, \delta_r \geq 0$ See References on skewed and heavy-tail(s) (Disclaimer: I am the author.) In R you can simulate, estimate, plot, etc. several Lambert W x F distributionswith the LambertW package. library(LambertW) library(RColorBrewer) # several heavy-tail parameters delta.v <- seq(0, 2, length = 11) x.grid <- seq(-5, 5, length = 100) col.v <- colorRampPalette(c("black", "orange"))(length(delta.v)) plot(x.grid, dnorm(x.grid), lwd = 2, type = "l", col = col.v[1], ylab = "") for (ii in seq_along(delta.v)) { lines(x.grid, dLambertW(x.grid, "normal", theta = list(delta = delta.v[ii], beta = c(0, 1))), col = col.v[ii]) } legend("topleft", paste(delta.v), col = col.v, lty = 1, title = "delta = ") It works similarly for a sequence of $\gamma$ to add skewness. And if you want to add skewness and heavy-tails then generate a sequence of $\delta_l$ and $\delta_r$.
Transformation to increase kurtosis and skewness of normal r.v
This can be done using Lambert W x F random variables / distributions. A Lambert W x F random variable (RV) is a non-linearly transformed (RV) X with distribution F. For F being the Normal distributi
Transformation to increase kurtosis and skewness of normal r.v This can be done using Lambert W x F random variables / distributions. A Lambert W x F random variable (RV) is a non-linearly transformed (RV) X with distribution F. For F being the Normal distribution and $\alpha = 1$, they reduce to Tukey's h distribution. The nice property of Lambert W x F distributions is that you can also go back from non-normal to Normal again; i.e., you can estimate parameters and Gaussianize() your data. They are implemented in the Lambert W x F transformations come in 3 flavors: skewed (type = 's') with skewness parameter $\gamma \in R$ heavy-tailed (type = 'h') with tail parameter $\delta \geq 0$ (and optional $\alpha$) skewed and heavy tailed (type = 'hh') with left/right tail parameter $\delta_l, \delta_r \geq 0$ See References on skewed and heavy-tail(s) (Disclaimer: I am the author.) In R you can simulate, estimate, plot, etc. several Lambert W x F distributionswith the LambertW package. library(LambertW) library(RColorBrewer) # several heavy-tail parameters delta.v <- seq(0, 2, length = 11) x.grid <- seq(-5, 5, length = 100) col.v <- colorRampPalette(c("black", "orange"))(length(delta.v)) plot(x.grid, dnorm(x.grid), lwd = 2, type = "l", col = col.v[1], ylab = "") for (ii in seq_along(delta.v)) { lines(x.grid, dLambertW(x.grid, "normal", theta = list(delta = delta.v[ii], beta = c(0, 1))), col = col.v[ii]) } legend("topleft", paste(delta.v), col = col.v, lty = 1, title = "delta = ") It works similarly for a sequence of $\gamma$ to add skewness. And if you want to add skewness and heavy-tails then generate a sequence of $\delta_l$ and $\delta_r$.
Transformation to increase kurtosis and skewness of normal r.v This can be done using Lambert W x F random variables / distributions. A Lambert W x F random variable (RV) is a non-linearly transformed (RV) X with distribution F. For F being the Normal distributi
13,086
Transformation to increase kurtosis and skewness of normal r.v
One such sequence is exponentiation to various degrees. E.g. library(moments) x <- rnorm(1000) #Normal data x2 <- 2^x #One transformation x3 <- 2^{x^2} #A stronger transformation test <- cbind(x, x2, x3) apply(test, 2, skewness) #Skewness for the three distributions apply(test, 2, kurtosis) #Kurtosis for the three distributions You could use $x^{1.1}, x^{1.2} \dots x^2$ to get intermediate degrees of transformation.
Transformation to increase kurtosis and skewness of normal r.v
One such sequence is exponentiation to various degrees. E.g. library(moments) x <- rnorm(1000) #Normal data x2 <- 2^x #One transformation x3 <- 2^{x^2} #A stronger transformation test <- cbind(x, x2,
Transformation to increase kurtosis and skewness of normal r.v One such sequence is exponentiation to various degrees. E.g. library(moments) x <- rnorm(1000) #Normal data x2 <- 2^x #One transformation x3 <- 2^{x^2} #A stronger transformation test <- cbind(x, x2, x3) apply(test, 2, skewness) #Skewness for the three distributions apply(test, 2, kurtosis) #Kurtosis for the three distributions You could use $x^{1.1}, x^{1.2} \dots x^2$ to get intermediate degrees of transformation.
Transformation to increase kurtosis and skewness of normal r.v One such sequence is exponentiation to various degrees. E.g. library(moments) x <- rnorm(1000) #Normal data x2 <- 2^x #One transformation x3 <- 2^{x^2} #A stronger transformation test <- cbind(x, x2,
13,087
Transformation to increase kurtosis and skewness of normal r.v
Same answer as @user10525 but in python import numpy as np from scipy.stats import norm def sinh_archsinh_transformation(x,epsilon,delta): return norm.pdf(np.sinh(delta*np.arcsinh(x)-epsilon))*delta*np.cosh(delta*np.arcsinh(x)-epsilon)/np.sqrt(1+np.power(x,2)) vec = np.arange(start=-15,stop=15+0.001,step=0.001) import matplotlib.pyplot as plt plt.plot(vec,sinh_archsinh_transformation(vec,0,1)) plt.plot(vec,sinh_archsinh_transformation(vec,1,1),color='red') plt.plot(vec,sinh_archsinh_transformation(vec,2,1),color='blue') plt.plot(vec,sinh_archsinh_transformation(vec,-1,1),color='red') plt.plot(vec,sinh_archsinh_transformation(vec,-2,1),color='blue') [
Transformation to increase kurtosis and skewness of normal r.v
Same answer as @user10525 but in python import numpy as np from scipy.stats import norm def sinh_archsinh_transformation(x,epsilon,delta): return norm.pdf(np.sinh(delta*np.arcsinh(x)-epsilon))*del
Transformation to increase kurtosis and skewness of normal r.v Same answer as @user10525 but in python import numpy as np from scipy.stats import norm def sinh_archsinh_transformation(x,epsilon,delta): return norm.pdf(np.sinh(delta*np.arcsinh(x)-epsilon))*delta*np.cosh(delta*np.arcsinh(x)-epsilon)/np.sqrt(1+np.power(x,2)) vec = np.arange(start=-15,stop=15+0.001,step=0.001) import matplotlib.pyplot as plt plt.plot(vec,sinh_archsinh_transformation(vec,0,1)) plt.plot(vec,sinh_archsinh_transformation(vec,1,1),color='red') plt.plot(vec,sinh_archsinh_transformation(vec,2,1),color='blue') plt.plot(vec,sinh_archsinh_transformation(vec,-1,1),color='red') plt.plot(vec,sinh_archsinh_transformation(vec,-2,1),color='blue') [
Transformation to increase kurtosis and skewness of normal r.v Same answer as @user10525 but in python import numpy as np from scipy.stats import norm def sinh_archsinh_transformation(x,epsilon,delta): return norm.pdf(np.sinh(delta*np.arcsinh(x)-epsilon))*del
13,088
Is there a way to maximize/minimize a custom function in R?
I wrote a post listing a few tutorials using optim. Here is a quote of the relevant section: "The combination of the R function optim and a custom created objective function, such as a minus log-likelihood function provides a powerful tool for parameter estimation of custom models. Scott Brown's tutorial includes an example of this. Ajay Shah has an example of writing a likelihood function and then getting a maximum likelihood estimate using optim. Benjamin Bolker has great material available on the web from his book Ecological Models and Data in R. PDFs, Rnw, and R code for early versions of the chapters are provided on the website. Chapter 6 (likelihood and all that) , 7 (the gory details of model fitting), and 8 (worked likelihood estimation examples). Brian Ripley has a set of slides on simulation and optimisation in R. In particular it provides a useful discussion of the various optimisation algorithms available using optim".
Is there a way to maximize/minimize a custom function in R?
I wrote a post listing a few tutorials using optim. Here is a quote of the relevant section: "The combination of the R function optim and a custom created objective function, such as a minus log-likel
Is there a way to maximize/minimize a custom function in R? I wrote a post listing a few tutorials using optim. Here is a quote of the relevant section: "The combination of the R function optim and a custom created objective function, such as a minus log-likelihood function provides a powerful tool for parameter estimation of custom models. Scott Brown's tutorial includes an example of this. Ajay Shah has an example of writing a likelihood function and then getting a maximum likelihood estimate using optim. Benjamin Bolker has great material available on the web from his book Ecological Models and Data in R. PDFs, Rnw, and R code for early versions of the chapters are provided on the website. Chapter 6 (likelihood and all that) , 7 (the gory details of model fitting), and 8 (worked likelihood estimation examples). Brian Ripley has a set of slides on simulation and optimisation in R. In particular it provides a useful discussion of the various optimisation algorithms available using optim".
Is there a way to maximize/minimize a custom function in R? I wrote a post listing a few tutorials using optim. Here is a quote of the relevant section: "The combination of the R function optim and a custom created objective function, such as a minus log-likel
13,089
Is there a way to maximize/minimize a custom function in R?
In addition to Jeromy Anglim's answer, I have some more links. Next to optim there is another function in base R that allows for what you want: nlminb. Check ?nlminb and ?optim for examples of the usage. There are a bunch of packages that can do optimizations. What I found most interesting were the packages optimx and, quite new, the neldermead package for different versions of the simplex algorithm. Furthermore, you might want to have a look at the CRAN Task View on Optimization for more packages Please note that my recommendations all assume that you have a deterministic function (i.e., no random noise). For functions that are not strictly deterministic (or too big) you would need to use algorithms such as simulated annealing or genetic algorithms. But the CRAN Task View should have what you need.
Is there a way to maximize/minimize a custom function in R?
In addition to Jeromy Anglim's answer, I have some more links. Next to optim there is another function in base R that allows for what you want: nlminb. Check ?nlminb and ?optim for examples of the usa
Is there a way to maximize/minimize a custom function in R? In addition to Jeromy Anglim's answer, I have some more links. Next to optim there is another function in base R that allows for what you want: nlminb. Check ?nlminb and ?optim for examples of the usage. There are a bunch of packages that can do optimizations. What I found most interesting were the packages optimx and, quite new, the neldermead package for different versions of the simplex algorithm. Furthermore, you might want to have a look at the CRAN Task View on Optimization for more packages Please note that my recommendations all assume that you have a deterministic function (i.e., no random noise). For functions that are not strictly deterministic (or too big) you would need to use algorithms such as simulated annealing or genetic algorithms. But the CRAN Task View should have what you need.
Is there a way to maximize/minimize a custom function in R? In addition to Jeromy Anglim's answer, I have some more links. Next to optim there is another function in base R that allows for what you want: nlminb. Check ?nlminb and ?optim for examples of the usa
13,090
Is there a way to maximize/minimize a custom function in R?
Is your function continuous and differentiable? You might be able to use optim, either with user-supplied derivatives or numerically approximated ones.
Is there a way to maximize/minimize a custom function in R?
Is your function continuous and differentiable? You might be able to use optim, either with user-supplied derivatives or numerically approximated ones.
Is there a way to maximize/minimize a custom function in R? Is your function continuous and differentiable? You might be able to use optim, either with user-supplied derivatives or numerically approximated ones.
Is there a way to maximize/minimize a custom function in R? Is your function continuous and differentiable? You might be able to use optim, either with user-supplied derivatives or numerically approximated ones.
13,091
When did MCMC become commonplace?
This paper by Christian (Xi'an) Robert and George Casella provides a nice summary of the history of MCMC. From the paper (emphasis is mine). What can be reasonably seen as the first MCMC algorithm is what we now call the Metropolis algorithm, published by Metropolis et al. (1953). It emanates from the same group of scientists who produced the Monte Carlo method, namely, the research scientists of Los Alamos, mostly physicists working on mathematical physics and the atomic bomb. The Metropolis algorithm was later generalized by Hastings (1970) and his student Peskun (1973,1981) Although somewhat removed from statistical inference in the classical sense and based on earlier techniques used in Statistical Physics, the landmark paper by Geman and Geman (1984) brought Gibbs sampling into the arena of statistical application. This paper is also responsible for the name Gibbs sampling In particular, Geman and Geman (1984) influenced Gelfand and Smith (1990) to write a paper that is the genuine starting point for an intensive use of MCMC methods by the main-stream statistical community. It sparked new inter-est in Bayesian methods, statistical computing, algorithms and stochastic processes through the use of computing algorithms such as the Gibbs sampler and the Metropolis–Hastings algorithm. Interestingly, the earlier paper by Tanner and Wong (1987) had essentially the same ingredients as Gelfand and Smith (1990), namely, the fact that simulating from the conditional distributions is sufficient to asymptotically simulate from the joint.This paper was considered important enough to be a discussion paper in the Journal of the American Statistical Association, but its impact was somehow limited, compared with Gelfand and Smith (1990). I couldn't find the number of journal articles published over time, but here is a Google Ngram plot for the number of mentions over time. It more or less agrees with the notion that MCMC became commonplace after the 1990 paper of Gelfand and Smith. Reference Robert, Christian, and George Casella. "A short history of Markov chain Monte Carlo: Subjective recollections from incomplete data." Statistical Science (2011): 102-115.
When did MCMC become commonplace?
This paper by Christian (Xi'an) Robert and George Casella provides a nice summary of the history of MCMC. From the paper (emphasis is mine). What can be reasonably seen as the first MCMC algorithm i
When did MCMC become commonplace? This paper by Christian (Xi'an) Robert and George Casella provides a nice summary of the history of MCMC. From the paper (emphasis is mine). What can be reasonably seen as the first MCMC algorithm is what we now call the Metropolis algorithm, published by Metropolis et al. (1953). It emanates from the same group of scientists who produced the Monte Carlo method, namely, the research scientists of Los Alamos, mostly physicists working on mathematical physics and the atomic bomb. The Metropolis algorithm was later generalized by Hastings (1970) and his student Peskun (1973,1981) Although somewhat removed from statistical inference in the classical sense and based on earlier techniques used in Statistical Physics, the landmark paper by Geman and Geman (1984) brought Gibbs sampling into the arena of statistical application. This paper is also responsible for the name Gibbs sampling In particular, Geman and Geman (1984) influenced Gelfand and Smith (1990) to write a paper that is the genuine starting point for an intensive use of MCMC methods by the main-stream statistical community. It sparked new inter-est in Bayesian methods, statistical computing, algorithms and stochastic processes through the use of computing algorithms such as the Gibbs sampler and the Metropolis–Hastings algorithm. Interestingly, the earlier paper by Tanner and Wong (1987) had essentially the same ingredients as Gelfand and Smith (1990), namely, the fact that simulating from the conditional distributions is sufficient to asymptotically simulate from the joint.This paper was considered important enough to be a discussion paper in the Journal of the American Statistical Association, but its impact was somehow limited, compared with Gelfand and Smith (1990). I couldn't find the number of journal articles published over time, but here is a Google Ngram plot for the number of mentions over time. It more or less agrees with the notion that MCMC became commonplace after the 1990 paper of Gelfand and Smith. Reference Robert, Christian, and George Casella. "A short history of Markov chain Monte Carlo: Subjective recollections from incomplete data." Statistical Science (2011): 102-115.
When did MCMC become commonplace? This paper by Christian (Xi'an) Robert and George Casella provides a nice summary of the history of MCMC. From the paper (emphasis is mine). What can be reasonably seen as the first MCMC algorithm i
13,092
When did MCMC become commonplace?
The excellent answer by knrumsey gives some history on the progression of important academic work in MCMC. One other aspect worth examining is the development of software to facilitate MCMC by the ordinary user. Statistical methods are often used mostly by specialists until they are implemented in software that allows the ordinary user to implement them without programming. For example, the software BUGS had its first release in 1997. That does not appear to have changed the growth trajectory in the N-Grams plot, but it may have been an influence in bringing the method into common usage among those users who found it intimidating to program their own routines.
When did MCMC become commonplace?
The excellent answer by knrumsey gives some history on the progression of important academic work in MCMC. One other aspect worth examining is the development of software to facilitate MCMC by the or
When did MCMC become commonplace? The excellent answer by knrumsey gives some history on the progression of important academic work in MCMC. One other aspect worth examining is the development of software to facilitate MCMC by the ordinary user. Statistical methods are often used mostly by specialists until they are implemented in software that allows the ordinary user to implement them without programming. For example, the software BUGS had its first release in 1997. That does not appear to have changed the growth trajectory in the N-Grams plot, but it may have been an influence in bringing the method into common usage among those users who found it intimidating to program their own routines.
When did MCMC become commonplace? The excellent answer by knrumsey gives some history on the progression of important academic work in MCMC. One other aspect worth examining is the development of software to facilitate MCMC by the or
13,093
Tensorflow Cross Entropy for Regression?
No, it doesn't make sense to use TensorFlow functions like tf.nn.sigmoid_cross_entropy_with_logits for a regression task. In TensorFlow, “cross-entropy” is shorthand (or jargon) for “categorical cross entropy.” Categorical cross entropy is an operation on probabilities. A regression problem attempts to predict continuous outcomes, rather than classifications. The jargon "cross-entropy" is a little misleading, because there are any number of cross-entropy loss functions; however, it's a convention in machine learning to refer to this particular loss as "cross-entropy" loss. If we look beyond the TensorFlow functions that you link to, then of course there are any number of possible cross-entropy functions. This is because the general concept of cross-entropy is about the comparison of two probability distributions. Depending on which two probability distributions you wish to compare, you may arrive at a different loss than the typical categorical cross-entropy loss. For example, the cross-entropy of a Gaussian target with some varying mean but fixed diagonal covariance reduces to mean-squared error. The general concept of cross-entropy is outlined in more detail in these questions: Do neural networks learn a function or a probability density function? How to construct a cross-entropy loss for general regression targets?
Tensorflow Cross Entropy for Regression?
No, it doesn't make sense to use TensorFlow functions like tf.nn.sigmoid_cross_entropy_with_logits for a regression task. In TensorFlow, “cross-entropy” is shorthand (or jargon) for “categorical cross
Tensorflow Cross Entropy for Regression? No, it doesn't make sense to use TensorFlow functions like tf.nn.sigmoid_cross_entropy_with_logits for a regression task. In TensorFlow, “cross-entropy” is shorthand (or jargon) for “categorical cross entropy.” Categorical cross entropy is an operation on probabilities. A regression problem attempts to predict continuous outcomes, rather than classifications. The jargon "cross-entropy" is a little misleading, because there are any number of cross-entropy loss functions; however, it's a convention in machine learning to refer to this particular loss as "cross-entropy" loss. If we look beyond the TensorFlow functions that you link to, then of course there are any number of possible cross-entropy functions. This is because the general concept of cross-entropy is about the comparison of two probability distributions. Depending on which two probability distributions you wish to compare, you may arrive at a different loss than the typical categorical cross-entropy loss. For example, the cross-entropy of a Gaussian target with some varying mean but fixed diagonal covariance reduces to mean-squared error. The general concept of cross-entropy is outlined in more detail in these questions: Do neural networks learn a function or a probability density function? How to construct a cross-entropy loss for general regression targets?
Tensorflow Cross Entropy for Regression? No, it doesn't make sense to use TensorFlow functions like tf.nn.sigmoid_cross_entropy_with_logits for a regression task. In TensorFlow, “cross-entropy” is shorthand (or jargon) for “categorical cross
13,094
Tensorflow Cross Entropy for Regression?
The answer given by @Sycorax is correct. However, it is worth mentioning that using (binary) cross-entropy in a regression task where the output values are in the range [0,1] is a valid and reasonable thing to do. Actually, it is used in image autoencoders (e.g. here and this paper). You might be interested to see a simple mathematical proof of why it works in this case in this answer.
Tensorflow Cross Entropy for Regression?
The answer given by @Sycorax is correct. However, it is worth mentioning that using (binary) cross-entropy in a regression task where the output values are in the range [0,1] is a valid and reasonable
Tensorflow Cross Entropy for Regression? The answer given by @Sycorax is correct. However, it is worth mentioning that using (binary) cross-entropy in a regression task where the output values are in the range [0,1] is a valid and reasonable thing to do. Actually, it is used in image autoencoders (e.g. here and this paper). You might be interested to see a simple mathematical proof of why it works in this case in this answer.
Tensorflow Cross Entropy for Regression? The answer given by @Sycorax is correct. However, it is worth mentioning that using (binary) cross-entropy in a regression task where the output values are in the range [0,1] is a valid and reasonable
13,095
Tensorflow Cross Entropy for Regression?
Deep learning frameworks often mix models and losses and refer to the cross-entropy of a multinomial model with softmax nonlinearity by cross_entropy, which is misleading. In general, you can define cross-entropy for arbitrary models. For a Gaussian model with varying mean but fixed diagonal covariance, it is equivalent to MSE. For a general covariance, cross-entropy would correspond to a squared Mahalanobis distance. For an exponential distribution, the cross-entropy loss would look like $$f_\theta(x) y - \log f_\theta(x),$$ where $y$ is continuous but non-negative. So yes, cross-entropy can be used for regression.
Tensorflow Cross Entropy for Regression?
Deep learning frameworks often mix models and losses and refer to the cross-entropy of a multinomial model with softmax nonlinearity by cross_entropy, which is misleading. In general, you can define c
Tensorflow Cross Entropy for Regression? Deep learning frameworks often mix models and losses and refer to the cross-entropy of a multinomial model with softmax nonlinearity by cross_entropy, which is misleading. In general, you can define cross-entropy for arbitrary models. For a Gaussian model with varying mean but fixed diagonal covariance, it is equivalent to MSE. For a general covariance, cross-entropy would correspond to a squared Mahalanobis distance. For an exponential distribution, the cross-entropy loss would look like $$f_\theta(x) y - \log f_\theta(x),$$ where $y$ is continuous but non-negative. So yes, cross-entropy can be used for regression.
Tensorflow Cross Entropy for Regression? Deep learning frameworks often mix models and losses and refer to the cross-entropy of a multinomial model with softmax nonlinearity by cross_entropy, which is misleading. In general, you can define c
13,096
Tensorflow Cross Entropy for Regression?
Unfortunately, the as of now accepted answer by @Sycorax, while detailed, is incorrect. Actually, a prime example of regression through categorical cross-entropy -- Wavenet -- has been implemented in TensorFlow. The principle is that you discretize your output space and then your model only predicts the respective bin; see Section 2.2 of the paper for an example in the sound modelling domain. So while technically the model performs classification, the eventual task solved is regression. An obvious downside is, that you lose output resolution. However, this may not be a problem (at least I think that the Google's artificial assistant spoke a very humanly voice) or you can play around with some post-processing, e.g. interpolating between the most probable bin and it's two neighbours. On the other hand, this approach makes the model much more powerful compared to the usual single-linear-unit output, i.e. allowing to express multi-modal predictions or to assess it's confidence. Note though that the latter can be naturally achieved by other means, e.g. by having an explicit (log)variance output as in Variational Autoencoders. Anyway, this approach does not scale well to more-dimensional output, because then the size of the output layer grows exponentially, making it both computational and modelling issue..
Tensorflow Cross Entropy for Regression?
Unfortunately, the as of now accepted answer by @Sycorax, while detailed, is incorrect. Actually, a prime example of regression through categorical cross-entropy -- Wavenet -- has been implemented in
Tensorflow Cross Entropy for Regression? Unfortunately, the as of now accepted answer by @Sycorax, while detailed, is incorrect. Actually, a prime example of regression through categorical cross-entropy -- Wavenet -- has been implemented in TensorFlow. The principle is that you discretize your output space and then your model only predicts the respective bin; see Section 2.2 of the paper for an example in the sound modelling domain. So while technically the model performs classification, the eventual task solved is regression. An obvious downside is, that you lose output resolution. However, this may not be a problem (at least I think that the Google's artificial assistant spoke a very humanly voice) or you can play around with some post-processing, e.g. interpolating between the most probable bin and it's two neighbours. On the other hand, this approach makes the model much more powerful compared to the usual single-linear-unit output, i.e. allowing to express multi-modal predictions or to assess it's confidence. Note though that the latter can be naturally achieved by other means, e.g. by having an explicit (log)variance output as in Variational Autoencoders. Anyway, this approach does not scale well to more-dimensional output, because then the size of the output layer grows exponentially, making it both computational and modelling issue..
Tensorflow Cross Entropy for Regression? Unfortunately, the as of now accepted answer by @Sycorax, while detailed, is incorrect. Actually, a prime example of regression through categorical cross-entropy -- Wavenet -- has been implemented in
13,097
Tensorflow Cross Entropy for Regression?
I've revisited this question as I now disagree with the answer I previously accepted. Cross entropy loss CAN be used in regression (although it isn't common.) It comes down to the fact that cross-entropy is a concept that only makes sense when comparing two probability distributions. You could consider a neural network which outputs a mean and standard deviation for a normal distribution as its prediction. It would then be punished more harshly for being more confident about bad predictions. So yes, it makes sense, but only if you're outputting a distribution in some sense. The link from @SiddharthShakya in a comment to my original question shows this.
Tensorflow Cross Entropy for Regression?
I've revisited this question as I now disagree with the answer I previously accepted. Cross entropy loss CAN be used in regression (although it isn't common.) It comes down to the fact that cross-entr
Tensorflow Cross Entropy for Regression? I've revisited this question as I now disagree with the answer I previously accepted. Cross entropy loss CAN be used in regression (although it isn't common.) It comes down to the fact that cross-entropy is a concept that only makes sense when comparing two probability distributions. You could consider a neural network which outputs a mean and standard deviation for a normal distribution as its prediction. It would then be punished more harshly for being more confident about bad predictions. So yes, it makes sense, but only if you're outputting a distribution in some sense. The link from @SiddharthShakya in a comment to my original question shows this.
Tensorflow Cross Entropy for Regression? I've revisited this question as I now disagree with the answer I previously accepted. Cross entropy loss CAN be used in regression (although it isn't common.) It comes down to the fact that cross-entr
13,098
Tensorflow Cross Entropy for Regression?
Yes, sure. What is Cross-Entropy? Let's think about what is Cross-Entropy (CE). CE cost in the context of PyTorch or another Frameworks can mean a different thing compare to MATH. Originally cross-entropy is some form of KL-divergence between distributions: https://sites.google.com/site/burlachenkok/articles/properties-of-kl-divergence Reasons: In the context of Machine Learning, the very often first argument for CE is typically vector from probability simplex such that it has one component equal to one. So input for CE is probability mass function (p.m.f.) in a discrete case. Inside PyTorch let's say there is an extra transformation called in STATS as "symmetric logistics transform" which $$\dfrac{exp(f_i(x)}{exp(f_1(x))+exp(f_2(x))+\dots + exp(f_k(x))}$$ What it's interesting it's a bijective mapping from Euclidane space into probabilistic simplex. Now, what is a regression? Regression in the context of probability theory means $E_{z}[y(x,z)|x]$ where by z I denote unobserved variables. In the context of machine learning, it means any predictor with an output single scalar variable or multiple scalar variables and it is not necessary conditional expectation. So as you see - there is already too much confusion with various terminology and basic terms in STATS and ML. If your model provides K scalar outputs (called sometimes logits) it can be plugged into CE with the symmetric logistic transformation. For the record - logits are just unbound scores from $\mathbb{R}$ such that class with maximum score is your prediction. I think the answer you can do whatever you want, and people do crazy things with Loss in STATS, Optimization, and Deep Learning Applications. I can not give you an exact answer because CE very often raised with classification models e.g. in Deep Learning or with Decision Trees. But if your question because you design such a system - it's better to allow more expressive power in Loss construction.
Tensorflow Cross Entropy for Regression?
Yes, sure. What is Cross-Entropy? Let's think about what is Cross-Entropy (CE). CE cost in the context of PyTorch or another Frameworks can mean a different thing compare to MATH. Originally cross-ent
Tensorflow Cross Entropy for Regression? Yes, sure. What is Cross-Entropy? Let's think about what is Cross-Entropy (CE). CE cost in the context of PyTorch or another Frameworks can mean a different thing compare to MATH. Originally cross-entropy is some form of KL-divergence between distributions: https://sites.google.com/site/burlachenkok/articles/properties-of-kl-divergence Reasons: In the context of Machine Learning, the very often first argument for CE is typically vector from probability simplex such that it has one component equal to one. So input for CE is probability mass function (p.m.f.) in a discrete case. Inside PyTorch let's say there is an extra transformation called in STATS as "symmetric logistics transform" which $$\dfrac{exp(f_i(x)}{exp(f_1(x))+exp(f_2(x))+\dots + exp(f_k(x))}$$ What it's interesting it's a bijective mapping from Euclidane space into probabilistic simplex. Now, what is a regression? Regression in the context of probability theory means $E_{z}[y(x,z)|x]$ where by z I denote unobserved variables. In the context of machine learning, it means any predictor with an output single scalar variable or multiple scalar variables and it is not necessary conditional expectation. So as you see - there is already too much confusion with various terminology and basic terms in STATS and ML. If your model provides K scalar outputs (called sometimes logits) it can be plugged into CE with the symmetric logistic transformation. For the record - logits are just unbound scores from $\mathbb{R}$ such that class with maximum score is your prediction. I think the answer you can do whatever you want, and people do crazy things with Loss in STATS, Optimization, and Deep Learning Applications. I can not give you an exact answer because CE very often raised with classification models e.g. in Deep Learning or with Decision Trees. But if your question because you design such a system - it's better to allow more expressive power in Loss construction.
Tensorflow Cross Entropy for Regression? Yes, sure. What is Cross-Entropy? Let's think about what is Cross-Entropy (CE). CE cost in the context of PyTorch or another Frameworks can mean a different thing compare to MATH. Originally cross-ent
13,099
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ
Yes, it would still be a fallacy. Here is a very simple figure showing four different situations. In each case red dots represent women, blue dot represent men, horizontal axis represents brain size and vertical axis represents IQ. I generated all four datasets such that: there is always the same difference in mean brain size between men ($22$) and women ($28$ - units are arbitrary). These are population means, but this difference is big enough to be statistically significant with any reasonable sample size; there is always zero difference in mean IQ between men and women (both $100$), and also zero correlation between gender and IQ; the strength of correlation between brain size and IQ varies as shown on the figure. In the upper-left subplot within-gender correlation (computed separately over men and separately over women, then averaged) is $0.3$, like in your quote. In the upper-right subplot overall correlation (over men and women together) is $0.3$. Note that your quote does not specify what the number of $0.33$ refers to. In the lower-left subplot within-gender correlation is $0.9$, like in your hypothetical example; in the lower-right subplot overall correlation is $0.9$. So you can have any value of correlation, and it does not matter if it's computed overall or within-group. Whatever the correlation coefficient, it is very well possible that there is zero correlation between gender and IQ and zero gender difference in mean IQ. Exploring the non-transitivity Let us explore the full space of possibilities, following the approach suggested by @kjetil. Suppose you have three variables $x_1, x_2, x_3$ and (without loss of generality) suppose that correlation between $x_1$ and $x_2$ is $a>0$ and correlation between $x_2$ and $x_3$ is $b>0$. The question is: what is the minimal possible positive value of the correlation $\lambda$ between $x_1$ and $x_3$? Does it sometimes have to be positive, or can it always be zero? The correlation matrix is $$\mathbf R = \left( \begin{array}{} 1&a&\lambda \\ a&1&b \\ \lambda &b&1 \end{array}\right)$$ and it has to have a non-negative determinant, i.e. $$\mathrm{det} \mathbf R = -\lambda^2 + 2ab\lambda - ( a^2+b^2-1) \ge 0,$$ meaning that $\lambda$ has to lie between $$ab \pm \sqrt{(1-a^2)(1-b^2)}.$$ If both roots are positive, then the minimal possible value of $\lambda$ is equal to the smaller root (and $\lambda$ has to be positive!). If zero is between these two roots, then $\lambda$ can be zero. We can solve this numerically and plot the minimal possible positive value of $\lambda$ for different $a$ and $b$: Informally, we could say that correlations would be transitive if given that $a>0$ and $b>0$, one could conclude that $\lambda>0$. We see that for most of values $a$ and $b$, $\lambda$ can be zero, meaning that correlations are non-transitive. However, for some sufficiently high values of $a$ and $b$, correlation $\lambda$ has to be positive, meaning that there is "some degree of transitivity" after all, but restricted to very high correlations only. Note that both correlations $a$ and $b$ have to be high. We can work out a precise condition for this "transitivity": as mentioned above, the smaller root should be positive, i.e. $ab - \sqrt{(1-a^2)(1-b^2)}>0$, which is equivalent to $a^2+b^2>1$. This is an equation of a circle! And indeed, if you look at the figure above, you will notice that the blue region forms a quarter of a circle. In your specific example, correlation between gender and brain size is quite moderate (perhaps $a=0.5$) and correlation between brain size and IQ is $b=0.33$, which is firmly within the blue region ($a^2+b^2<1$)meaning that $\lambda$ can be positive, negative, or zero. Relevant figure from the original study You wanted to avoid discussing gender and brains, but I cannot help pointing out that looking at the full figure from the original article (Gur et al. 1999), one can see that whereas there is no gender difference in verbal IQ score, there is an obvious and significant difference in spatial IQ score! Compare subplots D and F.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a
Yes, it would still be a fallacy. Here is a very simple figure showing four different situations. In each case red dots represent women, blue dot represent men, horizontal axis represents brain size a
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ Yes, it would still be a fallacy. Here is a very simple figure showing four different situations. In each case red dots represent women, blue dot represent men, horizontal axis represents brain size and vertical axis represents IQ. I generated all four datasets such that: there is always the same difference in mean brain size between men ($22$) and women ($28$ - units are arbitrary). These are population means, but this difference is big enough to be statistically significant with any reasonable sample size; there is always zero difference in mean IQ between men and women (both $100$), and also zero correlation between gender and IQ; the strength of correlation between brain size and IQ varies as shown on the figure. In the upper-left subplot within-gender correlation (computed separately over men and separately over women, then averaged) is $0.3$, like in your quote. In the upper-right subplot overall correlation (over men and women together) is $0.3$. Note that your quote does not specify what the number of $0.33$ refers to. In the lower-left subplot within-gender correlation is $0.9$, like in your hypothetical example; in the lower-right subplot overall correlation is $0.9$. So you can have any value of correlation, and it does not matter if it's computed overall or within-group. Whatever the correlation coefficient, it is very well possible that there is zero correlation between gender and IQ and zero gender difference in mean IQ. Exploring the non-transitivity Let us explore the full space of possibilities, following the approach suggested by @kjetil. Suppose you have three variables $x_1, x_2, x_3$ and (without loss of generality) suppose that correlation between $x_1$ and $x_2$ is $a>0$ and correlation between $x_2$ and $x_3$ is $b>0$. The question is: what is the minimal possible positive value of the correlation $\lambda$ between $x_1$ and $x_3$? Does it sometimes have to be positive, or can it always be zero? The correlation matrix is $$\mathbf R = \left( \begin{array}{} 1&a&\lambda \\ a&1&b \\ \lambda &b&1 \end{array}\right)$$ and it has to have a non-negative determinant, i.e. $$\mathrm{det} \mathbf R = -\lambda^2 + 2ab\lambda - ( a^2+b^2-1) \ge 0,$$ meaning that $\lambda$ has to lie between $$ab \pm \sqrt{(1-a^2)(1-b^2)}.$$ If both roots are positive, then the minimal possible value of $\lambda$ is equal to the smaller root (and $\lambda$ has to be positive!). If zero is between these two roots, then $\lambda$ can be zero. We can solve this numerically and plot the minimal possible positive value of $\lambda$ for different $a$ and $b$: Informally, we could say that correlations would be transitive if given that $a>0$ and $b>0$, one could conclude that $\lambda>0$. We see that for most of values $a$ and $b$, $\lambda$ can be zero, meaning that correlations are non-transitive. However, for some sufficiently high values of $a$ and $b$, correlation $\lambda$ has to be positive, meaning that there is "some degree of transitivity" after all, but restricted to very high correlations only. Note that both correlations $a$ and $b$ have to be high. We can work out a precise condition for this "transitivity": as mentioned above, the smaller root should be positive, i.e. $ab - \sqrt{(1-a^2)(1-b^2)}>0$, which is equivalent to $a^2+b^2>1$. This is an equation of a circle! And indeed, if you look at the figure above, you will notice that the blue region forms a quarter of a circle. In your specific example, correlation between gender and brain size is quite moderate (perhaps $a=0.5$) and correlation between brain size and IQ is $b=0.33$, which is firmly within the blue region ($a^2+b^2<1$)meaning that $\lambda$ can be positive, negative, or zero. Relevant figure from the original study You wanted to avoid discussing gender and brains, but I cannot help pointing out that looking at the full figure from the original article (Gur et al. 1999), one can see that whereas there is no gender difference in verbal IQ score, there is an obvious and significant difference in spatial IQ score! Compare subplots D and F.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a Yes, it would still be a fallacy. Here is a very simple figure showing four different situations. In each case red dots represent women, blue dot represent men, horizontal axis represents brain size a
13,100
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ
Let us define $x_1=\text{IQ}, x_2=\text{gender}$ and $x_3$ be some other variable (like brain volume) correlated to both. Let us assume that $$ \text{cor}(x_1, x_2)=\lambda, \\ \text{cor}(x_1,x_3)=\text{cor}(x_2, x_3)=\rho=0.9 $$ What is the smallest possible value for $\lambda$? A correlation matrix must be positive semi-definite, so its determinant must be nonnegative. That can be exploited to give an inequality. Let us try: The correlation matrix is $$ R=\begin{pmatrix} 1 & \lambda & \rho \\ \lambda & 1 & \rho \\ \rho & \rho & 1 \end{pmatrix} $$ Then we can calculate the determinant of $\rho$ by expanding along the first row: $$ \det R = 1\cdot (1-\rho^2) - \lambda \cdot (\lambda-\rho^2) + \rho \cdot (\lambda \rho - \rho) \\ = 1-\lambda^2 -2\rho^2 + 2\lambda \rho^2 \ge 0, $$ which leads to the inequality $\rho^2 \le \frac{\lambda+1}{2}$. The value $\rho=0.9$ leads to $ \lambda \ge 0.62$. Update: In response to comments I have updated somewhat the answer above. Now, what can we make of this? According to the calculations above, a correlation of 0.9 between IQ and brain volume (much larger than empirical). Then, the correlation between gender and IQ must be at least 0.62. What does that mean? In the comments some say this does not imply anything about mean differences between gender. But that cannot be true! Yes, for normally distributed variables we can assign correlation and means without relations. But gender is a zero-one variable, for such variable there is a relation between correlation and mean differences. Concretely, IQ is (say) normally distributed, while gender is discrete, zero-one. Let us assume its mean $p=0.5$ (realistically). Then a (say) positive correlation means that gender tends to be "higher" (that is, one) if IQ is higher. That cannot happen without there being a mean difference! Let us do the algebra: First, to simplify the algebra, let us center IQ at zero instead of the usual 100. That will not change any correlations or mean differences. Let $\mu_1 = \text{E}(x_1 | x_2=1)$ and $\mu_0 = \text{E}(x_1 | x_2=0)$. With $\mu=\text{E}(x_1)$ this means $\mu=0=\mu_1+\mu_0$ since $\mu_0 = -\mu_1$. We have $x_1 \sim \text{N}(\mu=0, \sigma^2)$ and $x_2$ is Bernoulli with $p=1/2$. $$ \text{corr}(x_1, x_2) = \frac{\text{E}(x_1-\mu)\text{E}(x_2-p)}{\sigma \cdot \frac12} \\ = \frac{\Delta}{2\sigma} $$ where $\Delta = \mu_1 - \mu_0 = 2\mu_1$. With the usual value (for IQ) $\sigma=10$ this gives that the correlation is equal to $\Delta/20$. So a correlation of 0.62 means an IQ difference of 12.4. So the posters claiming the correlation contain no information about IQ mean difference are wrong! That would be true if gender was a continuous variable, which it obviously not is. Note that this fact is related to the fact that for the binomial distribution, variance is a function of the mean (as it must be, since there is only one free parameter to vary). What we have done above is really extending this to covariance/correlation. But, according to the OP, the true value of $\rho=0.33$. Then the inequality becomes that $\lambda \ge -0.7822$, so $\lambda=0$ is a possible value. So in the true case, no conclusions about mean differences in IQ can be drawn from the correlation between IQ and brain volume.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a
Let us define $x_1=\text{IQ}, x_2=\text{gender}$ and $x_3$ be some other variable (like brain volume) correlated to both. Let us assume that $$ \text{cor}(x_1, x_2)=\lambda, \\ \text{cor}(x_1
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ Let us define $x_1=\text{IQ}, x_2=\text{gender}$ and $x_3$ be some other variable (like brain volume) correlated to both. Let us assume that $$ \text{cor}(x_1, x_2)=\lambda, \\ \text{cor}(x_1,x_3)=\text{cor}(x_2, x_3)=\rho=0.9 $$ What is the smallest possible value for $\lambda$? A correlation matrix must be positive semi-definite, so its determinant must be nonnegative. That can be exploited to give an inequality. Let us try: The correlation matrix is $$ R=\begin{pmatrix} 1 & \lambda & \rho \\ \lambda & 1 & \rho \\ \rho & \rho & 1 \end{pmatrix} $$ Then we can calculate the determinant of $\rho$ by expanding along the first row: $$ \det R = 1\cdot (1-\rho^2) - \lambda \cdot (\lambda-\rho^2) + \rho \cdot (\lambda \rho - \rho) \\ = 1-\lambda^2 -2\rho^2 + 2\lambda \rho^2 \ge 0, $$ which leads to the inequality $\rho^2 \le \frac{\lambda+1}{2}$. The value $\rho=0.9$ leads to $ \lambda \ge 0.62$. Update: In response to comments I have updated somewhat the answer above. Now, what can we make of this? According to the calculations above, a correlation of 0.9 between IQ and brain volume (much larger than empirical). Then, the correlation between gender and IQ must be at least 0.62. What does that mean? In the comments some say this does not imply anything about mean differences between gender. But that cannot be true! Yes, for normally distributed variables we can assign correlation and means without relations. But gender is a zero-one variable, for such variable there is a relation between correlation and mean differences. Concretely, IQ is (say) normally distributed, while gender is discrete, zero-one. Let us assume its mean $p=0.5$ (realistically). Then a (say) positive correlation means that gender tends to be "higher" (that is, one) if IQ is higher. That cannot happen without there being a mean difference! Let us do the algebra: First, to simplify the algebra, let us center IQ at zero instead of the usual 100. That will not change any correlations or mean differences. Let $\mu_1 = \text{E}(x_1 | x_2=1)$ and $\mu_0 = \text{E}(x_1 | x_2=0)$. With $\mu=\text{E}(x_1)$ this means $\mu=0=\mu_1+\mu_0$ since $\mu_0 = -\mu_1$. We have $x_1 \sim \text{N}(\mu=0, \sigma^2)$ and $x_2$ is Bernoulli with $p=1/2$. $$ \text{corr}(x_1, x_2) = \frac{\text{E}(x_1-\mu)\text{E}(x_2-p)}{\sigma \cdot \frac12} \\ = \frac{\Delta}{2\sigma} $$ where $\Delta = \mu_1 - \mu_0 = 2\mu_1$. With the usual value (for IQ) $\sigma=10$ this gives that the correlation is equal to $\Delta/20$. So a correlation of 0.62 means an IQ difference of 12.4. So the posters claiming the correlation contain no information about IQ mean difference are wrong! That would be true if gender was a continuous variable, which it obviously not is. Note that this fact is related to the fact that for the binomial distribution, variance is a function of the mean (as it must be, since there is only one free parameter to vary). What we have done above is really extending this to covariance/correlation. But, according to the OP, the true value of $\rho=0.33$. Then the inequality becomes that $\lambda \ge -0.7822$, so $\lambda=0$ is a possible value. So in the true case, no conclusions about mean differences in IQ can be drawn from the correlation between IQ and brain volume.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a Let us define $x_1=\text{IQ}, x_2=\text{gender}$ and $x_3$ be some other variable (like brain volume) correlated to both. Let us assume that $$ \text{cor}(x_1, x_2)=\lambda, \\ \text{cor}(x_1