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 |
|---|---|---|---|---|---|---|
38,701 | Why don't discrete time survival models require a random effect? | As Richard Hardy notes, discrete-time survival models can incorporate random effects. In many typical use cases, however, they aren't necessary. This is a similar issue for counting-process data in both continuous-time and discrete-time survival models.
If an individual can have at most one event and the modeling only involves covariate values in place at event times (as in Cox models or in many discrete-time models), then there is no intra-individual correlation to contend with. Therneau and Grambsch discuss this aspect of counting-process data in Section 3.7.1, page 70:
One concern that often arises is that observations [on the same individual] are "correlated," and would thus not be handled by standard methods. This is not actually an issue. The internal computations for a Cox model have a term for each unique death or event time; a given term involves sums over
those observations that are available or "at risk" at the select event date. Since the intervals for a particular subject, "Jones" say, do not overlap (assuming of course that Jones does not have a time machine, and could meet hirnself on the street), any given internal sum will involve at most one of the observations that represent Mr. Jones; that is, the sum will still be over a set of independent observations. For time-dependent covariates, the use of (start, stop] intervals is just a mechanism, a trick almost, that allows the program to select the correct x values for Jones at a given time. (When there are multiple events per subject the situation does become more complicated...).
If an individual can have more than 1 event or for types of parametric modeling that involve the entire survival function over time, then you would need to deal with intra-individual correlations. But simple binomial modeling when there can be at most 1 event per individual doesn't require that. | Why don't discrete time survival models require a random effect? | As Richard Hardy notes, discrete-time survival models can incorporate random effects. In many typical use cases, however, they aren't necessary. This is a similar issue for counting-process data in bo | Why don't discrete time survival models require a random effect?
As Richard Hardy notes, discrete-time survival models can incorporate random effects. In many typical use cases, however, they aren't necessary. This is a similar issue for counting-process data in both continuous-time and discrete-time survival models.
If an individual can have at most one event and the modeling only involves covariate values in place at event times (as in Cox models or in many discrete-time models), then there is no intra-individual correlation to contend with. Therneau and Grambsch discuss this aspect of counting-process data in Section 3.7.1, page 70:
One concern that often arises is that observations [on the same individual] are "correlated," and would thus not be handled by standard methods. This is not actually an issue. The internal computations for a Cox model have a term for each unique death or event time; a given term involves sums over
those observations that are available or "at risk" at the select event date. Since the intervals for a particular subject, "Jones" say, do not overlap (assuming of course that Jones does not have a time machine, and could meet hirnself on the street), any given internal sum will involve at most one of the observations that represent Mr. Jones; that is, the sum will still be over a set of independent observations. For time-dependent covariates, the use of (start, stop] intervals is just a mechanism, a trick almost, that allows the program to select the correct x values for Jones at a given time. (When there are multiple events per subject the situation does become more complicated...).
If an individual can have more than 1 event or for types of parametric modeling that involve the entire survival function over time, then you would need to deal with intra-individual correlations. But simple binomial modeling when there can be at most 1 event per individual doesn't require that. | Why don't discrete time survival models require a random effect?
As Richard Hardy notes, discrete-time survival models can incorporate random effects. In many typical use cases, however, they aren't necessary. This is a similar issue for counting-process data in bo |
38,702 | Why don't discrete time survival models require a random effect? | I don't see people adding random effects or specifying a correlation structure in discrete time survival models.
Tutz & Schmid "Modeling Discrete Time-to-Event Data" (2016) Chapter 9 "Frailty Models and Heterogeneity" covers both random and fixed effects models of the exact type you are describing. The motivation for random or fixed effects given there is about the same as you describe. Thus it is in conflict with your title question; discrete time survival models may well require a random effect.
Why have you not seen such models before? Perhaps since they may be difficult to estimate? (Just a guess.) At least I have had significant trouble with that; see "Simulating and estimating generalized mixed effects models: how to avoid convergence problems?". | Why don't discrete time survival models require a random effect? | I don't see people adding random effects or specifying a correlation structure in discrete time survival models.
Tutz & Schmid "Modeling Discrete Time-to-Event Data" (2016) Chapter 9 "Frailty Models | Why don't discrete time survival models require a random effect?
I don't see people adding random effects or specifying a correlation structure in discrete time survival models.
Tutz & Schmid "Modeling Discrete Time-to-Event Data" (2016) Chapter 9 "Frailty Models and Heterogeneity" covers both random and fixed effects models of the exact type you are describing. The motivation for random or fixed effects given there is about the same as you describe. Thus it is in conflict with your title question; discrete time survival models may well require a random effect.
Why have you not seen such models before? Perhaps since they may be difficult to estimate? (Just a guess.) At least I have had significant trouble with that; see "Simulating and estimating generalized mixed effects models: how to avoid convergence problems?". | Why don't discrete time survival models require a random effect?
I don't see people adding random effects or specifying a correlation structure in discrete time survival models.
Tutz & Schmid "Modeling Discrete Time-to-Event Data" (2016) Chapter 9 "Frailty Models |
38,703 | Simulation to estimate a conditional expectation | Unless the conditional density varies rapidly with the conditioning event, a brute-force rejection sample works.
Let's state the general problem. You wish to study the distribution of some function $f(X,Y)$ conditional on an event $\mathscr E$ which is either extremely rare or, as in this case, has zero probability (but positive density).
The idea is that with some care--there are geometric and probabilistic subtleties here (that are partially explored below)--you can "thicken" $\mathscr E$ by an amount $\delta$ to an event $\mathscr E^\prime = \mathscr E(\delta) \supset \mathscr E$ that has positive probability. Generate $(X,Y)$ from its joint distribution and reject any results not in $\mathscr E^\prime,$ then examine the empirical distribution of $f(X,Y)$ and compare it to what you expected theoretically.
This works provided the probability of $\mathscr E^\prime$ is not so small that it takes forever for randomly-generated $(X,Y)$ to fall within it. To obtain a sample of size $n,$ you will need (on average) to generate $N = n/\Pr(\mathscr E^\prime)$ values of $(X,Y).$ I recommend starting with a modest value of $N,$ generating values, and observing what $n$ turns out to be. Extrapolate from that to determine how many values you have time to generate. If it's too small, you will have to thicken $\mathscr E$ more -- and you can make a reasonable guess about how much more is needed based on this preliminary study.
Let's use your problem as an example. $X$ and $Y$ are independently Exponentially distributed. Because the parameter only establishes the unit of measurement, we may take it to be $1$ with no loss of generality. The function is $f(X,Y) = X+Y.$
A quick and dirty R implementation mirrors the strategy. This one examines the distribution of $X$ conditional on $X + Y \approx 0.5,$ using an amount $\delta = 0.05$ to thicken $\mathscr E:$
x <- rexp(1e4)
y <- rexp(1e4)
z <- x + y # z = f(x,y)
i <- abs(z - 0.5) <= 0.05 # Thicken E to E'
X <- data.frame(x = x[i], y = y[i], z = z[i]) # Reject results outside E'
Here is what the empirical $(x,y)$ scatterplot might look like:
with(X, plot(x, y))
The line $x+y=0.5$ is plotted for reference: it corresponds to the conditioning event $\mathscr E.$ The gray area (comprised of thousands of generated points) more or less fills out $\mathscr E^\prime.$
With such a simulation in hand, you can explore the conditional distribution of any $f(X,Y)$ in all the familiar ways, such as with a histogram
(the dashed line is the theoretical value) or an empirical CDF (ECDF)
The (faintly visible) dashed blue line is the theoretical distribution, shown for reference.
There are clear edge effects near $X = 0.5$ but those are understandable consequences of the fact that $Y \lt 0$ is not possible, thereby reducing the probability at that corner of $\mathscr E^\prime.$ (This is why examining the first scatterplot is helpful: it alerts you to such problem regions and helps you interpret the results.)
I mentioned the need for care. Let's illustrate that by showing what happens when the event $\mathscr E$ is thickened differently, using the same three figures.
I have allowed $\mathscr E^\prime$ to be thicker at smaller $X$ values than at larger ones, thereby relatively oversampling the smaller $X$ values. (This has a rationale: it eliminates the edge effects near $X = 0.5$) The histogram
and the ECDF
reflect that. They clearly differ from the theoretical result.
The moral of this example is that you need to understand what you're doing when you compute distributions conditional on events with zero probability! | Simulation to estimate a conditional expectation | Unless the conditional density varies rapidly with the conditioning event, a brute-force rejection sample works.
Let's state the general problem. You wish to study the distribution of some function $ | Simulation to estimate a conditional expectation
Unless the conditional density varies rapidly with the conditioning event, a brute-force rejection sample works.
Let's state the general problem. You wish to study the distribution of some function $f(X,Y)$ conditional on an event $\mathscr E$ which is either extremely rare or, as in this case, has zero probability (but positive density).
The idea is that with some care--there are geometric and probabilistic subtleties here (that are partially explored below)--you can "thicken" $\mathscr E$ by an amount $\delta$ to an event $\mathscr E^\prime = \mathscr E(\delta) \supset \mathscr E$ that has positive probability. Generate $(X,Y)$ from its joint distribution and reject any results not in $\mathscr E^\prime,$ then examine the empirical distribution of $f(X,Y)$ and compare it to what you expected theoretically.
This works provided the probability of $\mathscr E^\prime$ is not so small that it takes forever for randomly-generated $(X,Y)$ to fall within it. To obtain a sample of size $n,$ you will need (on average) to generate $N = n/\Pr(\mathscr E^\prime)$ values of $(X,Y).$ I recommend starting with a modest value of $N,$ generating values, and observing what $n$ turns out to be. Extrapolate from that to determine how many values you have time to generate. If it's too small, you will have to thicken $\mathscr E$ more -- and you can make a reasonable guess about how much more is needed based on this preliminary study.
Let's use your problem as an example. $X$ and $Y$ are independently Exponentially distributed. Because the parameter only establishes the unit of measurement, we may take it to be $1$ with no loss of generality. The function is $f(X,Y) = X+Y.$
A quick and dirty R implementation mirrors the strategy. This one examines the distribution of $X$ conditional on $X + Y \approx 0.5,$ using an amount $\delta = 0.05$ to thicken $\mathscr E:$
x <- rexp(1e4)
y <- rexp(1e4)
z <- x + y # z = f(x,y)
i <- abs(z - 0.5) <= 0.05 # Thicken E to E'
X <- data.frame(x = x[i], y = y[i], z = z[i]) # Reject results outside E'
Here is what the empirical $(x,y)$ scatterplot might look like:
with(X, plot(x, y))
The line $x+y=0.5$ is plotted for reference: it corresponds to the conditioning event $\mathscr E.$ The gray area (comprised of thousands of generated points) more or less fills out $\mathscr E^\prime.$
With such a simulation in hand, you can explore the conditional distribution of any $f(X,Y)$ in all the familiar ways, such as with a histogram
(the dashed line is the theoretical value) or an empirical CDF (ECDF)
The (faintly visible) dashed blue line is the theoretical distribution, shown for reference.
There are clear edge effects near $X = 0.5$ but those are understandable consequences of the fact that $Y \lt 0$ is not possible, thereby reducing the probability at that corner of $\mathscr E^\prime.$ (This is why examining the first scatterplot is helpful: it alerts you to such problem regions and helps you interpret the results.)
I mentioned the need for care. Let's illustrate that by showing what happens when the event $\mathscr E$ is thickened differently, using the same three figures.
I have allowed $\mathscr E^\prime$ to be thicker at smaller $X$ values than at larger ones, thereby relatively oversampling the smaller $X$ values. (This has a rationale: it eliminates the edge effects near $X = 0.5$) The histogram
and the ECDF
reflect that. They clearly differ from the theoretical result.
The moral of this example is that you need to understand what you're doing when you compute distributions conditional on events with zero probability! | Simulation to estimate a conditional expectation
Unless the conditional density varies rapidly with the conditioning event, a brute-force rejection sample works.
Let's state the general problem. You wish to study the distribution of some function $ |
38,704 | Simulation to estimate a conditional expectation | We could approach the problem using inverse transform sampling: generate random samples from the standard uniform distribution ($U$) and, given $X+Y$ that we specify, solve for $X$ and $Y$ for each $U$ using the hypothesized CDF. Then test whether $X$ and $Y$ are iid exponential variates.
Equivalently, we can reverse that approach by generating random $X$, $Y$ pairs, where the same exponential distribution is used within each pair. Then use the hypothesized CDF to transform them to $Z=\frac{X}{X+Y}$ (basically inverse transform sampling in reverse). Then simply test if $Z\sim U(0,1)$.
In R:
set.seed(94)
n <- 1e7L
X <- rexp(n)
Y <- rexp(n)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: z
#> D = 0.00029162, p-value = 0.3629
#> alternative hypothesis: two-sided
Check that the results hold while allowing the rate parameter to vary with each $X$, $Y$ pair:
theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: z
#> D = 0.00037478, p-value = 0.1205
#> alternative hypothesis: two-sided
Or plot the ECDF:
set.seed(94)
n <- 1e6L
X <- rexp(n)
Y <- rexp(n)
plot(ecdf(X/(X + Y)))
theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
plot(ecdf(X/(X + Y))) | Simulation to estimate a conditional expectation | We could approach the problem using inverse transform sampling: generate random samples from the standard uniform distribution ($U$) and, given $X+Y$ that we specify, solve for $X$ and $Y$ for each $U | Simulation to estimate a conditional expectation
We could approach the problem using inverse transform sampling: generate random samples from the standard uniform distribution ($U$) and, given $X+Y$ that we specify, solve for $X$ and $Y$ for each $U$ using the hypothesized CDF. Then test whether $X$ and $Y$ are iid exponential variates.
Equivalently, we can reverse that approach by generating random $X$, $Y$ pairs, where the same exponential distribution is used within each pair. Then use the hypothesized CDF to transform them to $Z=\frac{X}{X+Y}$ (basically inverse transform sampling in reverse). Then simply test if $Z\sim U(0,1)$.
In R:
set.seed(94)
n <- 1e7L
X <- rexp(n)
Y <- rexp(n)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: z
#> D = 0.00029162, p-value = 0.3629
#> alternative hypothesis: two-sided
Check that the results hold while allowing the rate parameter to vary with each $X$, $Y$ pair:
theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: z
#> D = 0.00037478, p-value = 0.1205
#> alternative hypothesis: two-sided
Or plot the ECDF:
set.seed(94)
n <- 1e6L
X <- rexp(n)
Y <- rexp(n)
plot(ecdf(X/(X + Y)))
theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
plot(ecdf(X/(X + Y))) | Simulation to estimate a conditional expectation
We could approach the problem using inverse transform sampling: generate random samples from the standard uniform distribution ($U$) and, given $X+Y$ that we specify, solve for $X$ and $Y$ for each $U |
38,705 | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model? | First off: Bias and variance of a model are measures of how bad your model is, while over- and underfitting are possible reasons for why your model is bad.
Definition of bias and variance
Bias and variance are defined e.g. here. The idea is this: You want to learn some function $f(x)$. You have a lot of datasets
$\{D_i\}_{i=1}^s$, $D_i = ((x_{i1}, y_{i1}), \ldots, (x_{in}, y_{in}))$, all of size $n$, and all drawn from the same population. Let's denote this set of datasets with $S$. Then you train your predictor $\hat f$ on each dataset $D_i$, so you end up with $s$ different predictors $\hat f_k, k=1,\ldots,s$.
Next, you fix an $x$ and you compute the sample mean and the sample variance of all your $s$ predictors on this single $x$:
$$
\begin{align}
m_{\hat f}(x) &:= avg_i(\hat f_i(x))\\
s^2_{\hat f}(x) &:= avg_i((\hat f_i(x) - m_{\hat f}(x))^2)
\end{align}
$$
Finally, you define the bias as the difference between $m_{\hat f}$ and the actual value $f(x)$:
$$
bias_{\hat f}(x) = m_{\hat f}(x) - f(x).
$$
Of course, the real value $f(x)$ is not known, so you cannot really compute the bias. Nevertheless, you can still reason about it.
(To be precise, the real bias and variance of the model at $x$ would only be obtained with $s\to\infty$.)
Note again, that this is dependent on $x$, i.e. each $x$ can have a different bias and variance. So we don't talk about the variance in a dataset, but about the variance of the predictions $\hat{f}_i$ at $x$ when learning from many different datasets $D_i$ from the same population. If you want to, you could average those over all $x$ which would then yield the average bias and variance of your model.
Bias-Variance Tradeoff
Often, but certainly not always, changes to your learning procedure that decrease the bias would increase the variance, and the other way around, hence the name bias-variance tradeoff. E.g., reducing the neighborhood size in nearest-neighbor methods would decrease the bias but increase the variance. However, increasing the size of your training dataset would often reduce both your model bias and variance.
Connection between over- and underfitting and bias and variance
Overfitting usually increases the variance, while underfitting increases the bias: Overfitting means that you have fitted an overly complex model to your training data, so a small variance in your training set can result in a large variance of $\hat f(x_{test})$ at your test data covariate $x_{test}$. Underfitting, on the other hand, occurs if you fit an overly simple model, that is not capable of adjusting to the peculiarities of your data. So, while $\hat f(x_{test})$ will not vary much at your test data covariate $x_{test}$ (because, being simple, it doesn't have the capacity to), it will often not be capable of "reaching" all points in your dataset, hence large bias. | Why do we say that the model has a high variance when variance is actually the measure of spread of | First off: Bias and variance of a model are measures of how bad your model is, while over- and underfitting are possible reasons for why your model is bad.
Definition of bias and variance
Bias and var | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model?
First off: Bias and variance of a model are measures of how bad your model is, while over- and underfitting are possible reasons for why your model is bad.
Definition of bias and variance
Bias and variance are defined e.g. here. The idea is this: You want to learn some function $f(x)$. You have a lot of datasets
$\{D_i\}_{i=1}^s$, $D_i = ((x_{i1}, y_{i1}), \ldots, (x_{in}, y_{in}))$, all of size $n$, and all drawn from the same population. Let's denote this set of datasets with $S$. Then you train your predictor $\hat f$ on each dataset $D_i$, so you end up with $s$ different predictors $\hat f_k, k=1,\ldots,s$.
Next, you fix an $x$ and you compute the sample mean and the sample variance of all your $s$ predictors on this single $x$:
$$
\begin{align}
m_{\hat f}(x) &:= avg_i(\hat f_i(x))\\
s^2_{\hat f}(x) &:= avg_i((\hat f_i(x) - m_{\hat f}(x))^2)
\end{align}
$$
Finally, you define the bias as the difference between $m_{\hat f}$ and the actual value $f(x)$:
$$
bias_{\hat f}(x) = m_{\hat f}(x) - f(x).
$$
Of course, the real value $f(x)$ is not known, so you cannot really compute the bias. Nevertheless, you can still reason about it.
(To be precise, the real bias and variance of the model at $x$ would only be obtained with $s\to\infty$.)
Note again, that this is dependent on $x$, i.e. each $x$ can have a different bias and variance. So we don't talk about the variance in a dataset, but about the variance of the predictions $\hat{f}_i$ at $x$ when learning from many different datasets $D_i$ from the same population. If you want to, you could average those over all $x$ which would then yield the average bias and variance of your model.
Bias-Variance Tradeoff
Often, but certainly not always, changes to your learning procedure that decrease the bias would increase the variance, and the other way around, hence the name bias-variance tradeoff. E.g., reducing the neighborhood size in nearest-neighbor methods would decrease the bias but increase the variance. However, increasing the size of your training dataset would often reduce both your model bias and variance.
Connection between over- and underfitting and bias and variance
Overfitting usually increases the variance, while underfitting increases the bias: Overfitting means that you have fitted an overly complex model to your training data, so a small variance in your training set can result in a large variance of $\hat f(x_{test})$ at your test data covariate $x_{test}$. Underfitting, on the other hand, occurs if you fit an overly simple model, that is not capable of adjusting to the peculiarities of your data. So, while $\hat f(x_{test})$ will not vary much at your test data covariate $x_{test}$ (because, being simple, it doesn't have the capacity to), it will often not be capable of "reaching" all points in your dataset, hence large bias. | Why do we say that the model has a high variance when variance is actually the measure of spread of
First off: Bias and variance of a model are measures of how bad your model is, while over- and underfitting are possible reasons for why your model is bad.
Definition of bias and variance
Bias and var |
38,706 | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model? | When we are building a machine learning model, we have to take two factors into account:
On one hand, we want the predictions given by the model to be as accurate as possible, this means that we want the model to have as little error as possible.
On the other hand, we know that the observations in our data set are likely to have errors: either measurement errors, or they are influenced by some aspect that we do not take into account in the model.
So with our model we want to achieve a compromise, we want it to be able to capture the general trend of the data, without being influenced by the specific errors of the set with which we train it. An example always helps,
If our model is too general, we will be in the situation of the left image, underfitting, and not really capturing the behavior of the data.
But if our model is not general enough, we will be in the situation of the middle image, overfitting, and we will be including in the model specific errors of the observations in the trainset. That is, a change in our data set will produce a very large change in the model.
It is clear that the best model is the one in the image on the right, because it captures the general behavior (that curved trend) without being influenced by all the specific errors of the observations.
So finally, the variance in a model tells us how variable the model is. The larger the variance, the more abrupt changes, ups and downs we will see in the model's predictions. If the variance is very small, the model is very stable and under-fitted. But if it is too large, the model is too variable and over-fitted. We look for a middle ground between the two. | Why do we say that the model has a high variance when variance is actually the measure of spread of | When we are building a machine learning model, we have to take two factors into account:
On one hand, we want the predictions given by the model to be as accurate as possible, this means that we want | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model?
When we are building a machine learning model, we have to take two factors into account:
On one hand, we want the predictions given by the model to be as accurate as possible, this means that we want the model to have as little error as possible.
On the other hand, we know that the observations in our data set are likely to have errors: either measurement errors, or they are influenced by some aspect that we do not take into account in the model.
So with our model we want to achieve a compromise, we want it to be able to capture the general trend of the data, without being influenced by the specific errors of the set with which we train it. An example always helps,
If our model is too general, we will be in the situation of the left image, underfitting, and not really capturing the behavior of the data.
But if our model is not general enough, we will be in the situation of the middle image, overfitting, and we will be including in the model specific errors of the observations in the trainset. That is, a change in our data set will produce a very large change in the model.
It is clear that the best model is the one in the image on the right, because it captures the general behavior (that curved trend) without being influenced by all the specific errors of the observations.
So finally, the variance in a model tells us how variable the model is. The larger the variance, the more abrupt changes, ups and downs we will see in the model's predictions. If the variance is very small, the model is very stable and under-fitted. But if it is too large, the model is too variable and over-fitted. We look for a middle ground between the two. | Why do we say that the model has a high variance when variance is actually the measure of spread of
When we are building a machine learning model, we have to take two factors into account:
On one hand, we want the predictions given by the model to be as accurate as possible, this means that we want |
38,707 | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model? | The other answers makes a great illustration, thus I want to answer your "... when variance is not a model's property."
It can be a bit confusing since a model is not "data" as such, but a "thing" that produces data. But, since a model is used to produce data, when we talk about a "model having big variance" we actually, losely speaking, mean that "the data the model produces have a high variance".
Consider the following; say you have a model which always predicts the number 5 e.g
X = [1,2,3,4,5,6,7]
model(X) #[5,5,5,5,5,5,5]
No matter what data you use put into the model it will always output $5$, thus we would say that your model does not vary at all (eventhough it is actually the output that doesn't vary, but since the output is a function of the model, then the model doesn't vary at all either).
Now, say you have a model which does the exact opposite, it varies a lot
X = [1,2,3,4,5,6,7]
model(X) #[-12,0,30000,9,-10000,2500,13]
as you can see (relatively) small changes in your input data results in huge difference in your ouput data (the model has a big variance). With a good model, we would expect that inputs that are close to eachother would result in outputs that are close to eachother aswell, which is not the case here.
These two scenarios corresponds to underfit/overfit respectively (see @Álvaro Méndez Civieta great plots), where the overfitted-model jumps a lot (high variance in the output) and the underfitted model doesn't move at all (or very little). | Why do we say that the model has a high variance when variance is actually the measure of spread of | The other answers makes a great illustration, thus I want to answer your "... when variance is not a model's property."
It can be a bit confusing since a model is not "data" as such, but a "thing" tha | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model?
The other answers makes a great illustration, thus I want to answer your "... when variance is not a model's property."
It can be a bit confusing since a model is not "data" as such, but a "thing" that produces data. But, since a model is used to produce data, when we talk about a "model having big variance" we actually, losely speaking, mean that "the data the model produces have a high variance".
Consider the following; say you have a model which always predicts the number 5 e.g
X = [1,2,3,4,5,6,7]
model(X) #[5,5,5,5,5,5,5]
No matter what data you use put into the model it will always output $5$, thus we would say that your model does not vary at all (eventhough it is actually the output that doesn't vary, but since the output is a function of the model, then the model doesn't vary at all either).
Now, say you have a model which does the exact opposite, it varies a lot
X = [1,2,3,4,5,6,7]
model(X) #[-12,0,30000,9,-10000,2500,13]
as you can see (relatively) small changes in your input data results in huge difference in your ouput data (the model has a big variance). With a good model, we would expect that inputs that are close to eachother would result in outputs that are close to eachother aswell, which is not the case here.
These two scenarios corresponds to underfit/overfit respectively (see @Álvaro Méndez Civieta great plots), where the overfitted-model jumps a lot (high variance in the output) and the underfitted model doesn't move at all (or very little). | Why do we say that the model has a high variance when variance is actually the measure of spread of
The other answers makes a great illustration, thus I want to answer your "... when variance is not a model's property."
It can be a bit confusing since a model is not "data" as such, but a "thing" tha |
38,708 | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model? | TL;DR the variance is computed over hypothetical other randomly sampled training datasets.
You can find the technical definition in the other answers, I try to give a bit of background understanding here.
Bias and variance (in this usage) ultimately come from a frequentist conceptual framework, which might be a bit counter-intuitive if you were taught in a Bayesian machine learning style (the opposite kind of problem also comes up, and perhaps even more frequently).
The main idea in frequentist statistics is to understand/imagine (training) data to be random, not fixed (and parameters fixed, but that's not important now). Many frequentist concepts in the end boil down to counterfactual thought experiments: what would be our result if our input data were different. If you come from a Bayesian perspective this may be strange, since the input data is what it is, and we want to train a model on this data, who cares what would happen if we had different data, right? In a way, yes, but it is still useful to think about whether our learning process is brittle and would output something very different if we had somewhat different training data.
For bias and variance, we imagine what would happen if you resampled a new training set, trained the model on that data and made your predictions anew. Rinse and repeat, and record what your outputs are and see how much spread (variance) they have as you vary the training data.
Outside of toy models that can be prodded and analyzed arbitrarily, all this is more of a thought experiment.
In the real world, your data is fixed, and you can't just sample arbitrarily many independent training sets to measure bias and variance. They are rather theoretical concepts to be aware of and terminology to use in communication about how your model is performing and what the reason for bad performance may be. Cross-validation is a common real-world approximation to analyze if your model is sensitive in this way to the exact training data. But the different CV folds are not independently sampled, so it's just an approximation. | Why do we say that the model has a high variance when variance is actually the measure of spread of | TL;DR the variance is computed over hypothetical other randomly sampled training datasets.
You can find the technical definition in the other answers, I try to give a bit of background understanding h | Why do we say that the model has a high variance when variance is actually the measure of spread of the data and not some property of the model?
TL;DR the variance is computed over hypothetical other randomly sampled training datasets.
You can find the technical definition in the other answers, I try to give a bit of background understanding here.
Bias and variance (in this usage) ultimately come from a frequentist conceptual framework, which might be a bit counter-intuitive if you were taught in a Bayesian machine learning style (the opposite kind of problem also comes up, and perhaps even more frequently).
The main idea in frequentist statistics is to understand/imagine (training) data to be random, not fixed (and parameters fixed, but that's not important now). Many frequentist concepts in the end boil down to counterfactual thought experiments: what would be our result if our input data were different. If you come from a Bayesian perspective this may be strange, since the input data is what it is, and we want to train a model on this data, who cares what would happen if we had different data, right? In a way, yes, but it is still useful to think about whether our learning process is brittle and would output something very different if we had somewhat different training data.
For bias and variance, we imagine what would happen if you resampled a new training set, trained the model on that data and made your predictions anew. Rinse and repeat, and record what your outputs are and see how much spread (variance) they have as you vary the training data.
Outside of toy models that can be prodded and analyzed arbitrarily, all this is more of a thought experiment.
In the real world, your data is fixed, and you can't just sample arbitrarily many independent training sets to measure bias and variance. They are rather theoretical concepts to be aware of and terminology to use in communication about how your model is performing and what the reason for bad performance may be. Cross-validation is a common real-world approximation to analyze if your model is sensitive in this way to the exact training data. But the different CV folds are not independently sampled, so it's just an approximation. | Why do we say that the model has a high variance when variance is actually the measure of spread of
TL;DR the variance is computed over hypothetical other randomly sampled training datasets.
You can find the technical definition in the other answers, I try to give a bit of background understanding h |
38,709 | Permutation feature importance on Train vs Validation set | The difference in the observed importance of some features when running the feature importance algorithm on Train and Test sets might indicate a tendency of the model to overfit using these features. This is indeed closely related to your intuition on the noise issue.
In other words, your model is over-tuned w.r.t features c,d,f,g,I.
Running feature importance on train or test sets hasn't been addressed enough in literature. However, a good, albeit simple, analysis of this issue is provided in this blogpost. | Permutation feature importance on Train vs Validation set | The difference in the observed importance of some features when running the feature importance algorithm on Train and Test sets might indicate a tendency of the model to overfit using these features. | Permutation feature importance on Train vs Validation set
The difference in the observed importance of some features when running the feature importance algorithm on Train and Test sets might indicate a tendency of the model to overfit using these features. This is indeed closely related to your intuition on the noise issue.
In other words, your model is over-tuned w.r.t features c,d,f,g,I.
Running feature importance on train or test sets hasn't been addressed enough in literature. However, a good, albeit simple, analysis of this issue is provided in this blogpost. | Permutation feature importance on Train vs Validation set
The difference in the observed importance of some features when running the feature importance algorithm on Train and Test sets might indicate a tendency of the model to overfit using these features. |
38,710 | Permutation feature importance on Train vs Validation set | First: ignore the results you have for the training set, they are worthless. Who cares how good a feature is at predicting for records that built the model?
Second: At this point you can’t do anything with features c,d,f,g. You’ve already built your model, yes these features are not useful in predicting the values for your test set, but if you were to remove them now, your test set would become part of the training process and you would be without a test set. All you can use this for at this point is to know that these features are uninformative for your model. To remove them and retrain the model would be akin to stepwise regression which we all know is bad.
If you wanted to use this measure in order to select features and improve your model I believe something like this would work: split your data into train/validation/test. Then split train into train/test, call it train2 and test2 I guess. Build a model on train2 and test the feature importance on test2. You could then remove any irrelevant features. Now continue as usual on train/test/validation as usual. | Permutation feature importance on Train vs Validation set | First: ignore the results you have for the training set, they are worthless. Who cares how good a feature is at predicting for records that built the model?
Second: At this point you can’t do anything | Permutation feature importance on Train vs Validation set
First: ignore the results you have for the training set, they are worthless. Who cares how good a feature is at predicting for records that built the model?
Second: At this point you can’t do anything with features c,d,f,g. You’ve already built your model, yes these features are not useful in predicting the values for your test set, but if you were to remove them now, your test set would become part of the training process and you would be without a test set. All you can use this for at this point is to know that these features are uninformative for your model. To remove them and retrain the model would be akin to stepwise regression which we all know is bad.
If you wanted to use this measure in order to select features and improve your model I believe something like this would work: split your data into train/validation/test. Then split train into train/test, call it train2 and test2 I guess. Build a model on train2 and test the feature importance on test2. You could then remove any irrelevant features. Now continue as usual on train/test/validation as usual. | Permutation feature importance on Train vs Validation set
First: ignore the results you have for the training set, they are worthless. Who cares how good a feature is at predicting for records that built the model?
Second: At this point you can’t do anything |
38,711 | Permutation feature importance on Train vs Validation set | Well, let's think at what those numbers actually mean.
If we take feature g for example, we know that our model relies on it a bit. So much that if you shuffle its values when making predictions on train data, your model performance drops by around $0.002$ (if I am correct).
However, when we do the same thing and shuffle it before predicting unseen data, the model performace is on average unchanged, which means that the feature has no predictive power on your target, and that the importance it has with training data comes from using some pattern of your training data that does not generalize (aka, you are overfitting).
Random forests tend to build very deep trees (possibly, up to a point where no split is possible). This means that even if you have a feature that is just white noise some trees will end up using it for splits at some point because they will see some pattern in it. This means that overall, it is likely even for noise features to have a positive permutation importance on the training data - and this is why the permutation importance you should really care about is on you validation set!
Now, what should you do next? Random Forests are somewhat resistant to this kind of overfitting, and having a few variables that contain only noise is not too detrimental to the overall performance, as long as their relative importance (on the training data) is not excessive, and there is not too many of them.
However, as you now know that those features are useless for your regression (and in general as good practice), the best option would be to remove them and retrain your model. | Permutation feature importance on Train vs Validation set | Well, let's think at what those numbers actually mean.
If we take feature g for example, we know that our model relies on it a bit. So much that if you shuffle its values when making predictions on t | Permutation feature importance on Train vs Validation set
Well, let's think at what those numbers actually mean.
If we take feature g for example, we know that our model relies on it a bit. So much that if you shuffle its values when making predictions on train data, your model performance drops by around $0.002$ (if I am correct).
However, when we do the same thing and shuffle it before predicting unseen data, the model performace is on average unchanged, which means that the feature has no predictive power on your target, and that the importance it has with training data comes from using some pattern of your training data that does not generalize (aka, you are overfitting).
Random forests tend to build very deep trees (possibly, up to a point where no split is possible). This means that even if you have a feature that is just white noise some trees will end up using it for splits at some point because they will see some pattern in it. This means that overall, it is likely even for noise features to have a positive permutation importance on the training data - and this is why the permutation importance you should really care about is on you validation set!
Now, what should you do next? Random Forests are somewhat resistant to this kind of overfitting, and having a few variables that contain only noise is not too detrimental to the overall performance, as long as their relative importance (on the training data) is not excessive, and there is not too many of them.
However, as you now know that those features are useless for your regression (and in general as good practice), the best option would be to remove them and retrain your model. | Permutation feature importance on Train vs Validation set
Well, let's think at what those numbers actually mean.
If we take feature g for example, we know that our model relies on it a bit. So much that if you shuffle its values when making predictions on t |
38,712 | Measuring Standard Error of two or more coefficients combined | 1) A linear combination a of the coefficients has a standard error of $\sqrt(a'Va)$ where $V$ is the variance covariance matrix of the coefficients. (See this wikipedia link on the variance of a linear combination of random variables.) We can get $V$ using vcov in R so using fm from the reproducible code in the Note at the end we have:
a <- c(0, 1, 0, 1, 0, 0)
c(sqrt(t(a) %*% vcov(fm) %*% a))
## [1] 2.940084
2) delta method The delta method can be used to get an approximate standard error of a general (differentiable) nonlinear function of the coefficients. When the function is linear, as it is here, then the Taylor series approximation underlying the delta method is exact and gives the same result as above.
library(alr3)
deltaMethod(fm, "x1dog+x2happy")
## Estimate SE 2.5 % 97.5 %
## x1dog + x2happy -0.2095575 2.940084 -5.972016 5.552901
3) general linear hypothesis Testing the hypothesis $a'\beta = 0$ (where $\beta$ is the coefficient vector) involves using the desired standard error in the denominator of the t-test suggesting that we look for a function to perform such hypothesis test. In fact, running glht with the hypothesis x1dog + x2happy = 0 does display the desired standard error, as shown below:
library(multcomp)
summary(glht(fm, "x1dog + x2happy = 0"))
giving the following where the Std. Error shown is the standard error of x1dog + x2 happy. It equals the standard error computed in (1) and (2).
Simultaneous Tests for General Linear Hypotheses
Fit: lm(formula = y ~ x1 + x2 + x3)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
x1dog + x2happy == 0 -0.2096 2.9401 -0.071 0.948
(Adjusted p values reported -- single-step method)
Note
We assume the input is the following where we use set.seed to make it reproducible.
set.seed(123)
x1 <- as.factor(c(rep("dog", 3), rep("cat", 3), rep("mouse", 3)))
x2 <- as.factor(rep(c("happy", "sad", "angry"), 3))
x3 <- rnorm(9, 0, 1) + runif(9, 3, 5)
y <- rnorm(9, 10, 2)
fm <- lm(y ~ x1 + x2 + x3)
coef(fm)
## (Intercept) x1dog x1mouse x2happy x2sad x3
## 12.4103736 0.1637373 -1.3375086 -0.3732948 -1.4833220 -0.3470490 | Measuring Standard Error of two or more coefficients combined | 1) A linear combination a of the coefficients has a standard error of $\sqrt(a'Va)$ where $V$ is the variance covariance matrix of the coefficients. (See this wikipedia link on the variance of a line | Measuring Standard Error of two or more coefficients combined
1) A linear combination a of the coefficients has a standard error of $\sqrt(a'Va)$ where $V$ is the variance covariance matrix of the coefficients. (See this wikipedia link on the variance of a linear combination of random variables.) We can get $V$ using vcov in R so using fm from the reproducible code in the Note at the end we have:
a <- c(0, 1, 0, 1, 0, 0)
c(sqrt(t(a) %*% vcov(fm) %*% a))
## [1] 2.940084
2) delta method The delta method can be used to get an approximate standard error of a general (differentiable) nonlinear function of the coefficients. When the function is linear, as it is here, then the Taylor series approximation underlying the delta method is exact and gives the same result as above.
library(alr3)
deltaMethod(fm, "x1dog+x2happy")
## Estimate SE 2.5 % 97.5 %
## x1dog + x2happy -0.2095575 2.940084 -5.972016 5.552901
3) general linear hypothesis Testing the hypothesis $a'\beta = 0$ (where $\beta$ is the coefficient vector) involves using the desired standard error in the denominator of the t-test suggesting that we look for a function to perform such hypothesis test. In fact, running glht with the hypothesis x1dog + x2happy = 0 does display the desired standard error, as shown below:
library(multcomp)
summary(glht(fm, "x1dog + x2happy = 0"))
giving the following where the Std. Error shown is the standard error of x1dog + x2 happy. It equals the standard error computed in (1) and (2).
Simultaneous Tests for General Linear Hypotheses
Fit: lm(formula = y ~ x1 + x2 + x3)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
x1dog + x2happy == 0 -0.2096 2.9401 -0.071 0.948
(Adjusted p values reported -- single-step method)
Note
We assume the input is the following where we use set.seed to make it reproducible.
set.seed(123)
x1 <- as.factor(c(rep("dog", 3), rep("cat", 3), rep("mouse", 3)))
x2 <- as.factor(rep(c("happy", "sad", "angry"), 3))
x3 <- rnorm(9, 0, 1) + runif(9, 3, 5)
y <- rnorm(9, 10, 2)
fm <- lm(y ~ x1 + x2 + x3)
coef(fm)
## (Intercept) x1dog x1mouse x2happy x2sad x3
## 12.4103736 0.1637373 -1.3375086 -0.3732948 -1.4833220 -0.3470490 | Measuring Standard Error of two or more coefficients combined
1) A linear combination a of the coefficients has a standard error of $\sqrt(a'Va)$ where $V$ is the variance covariance matrix of the coefficients. (See this wikipedia link on the variance of a line |
38,713 | Measuring Standard Error of two or more coefficients combined | The sum of two correlated (jointly-)normal variables, $Z=X+Y$, is itself normal, $N(\mu_{X+Y},\sigma_{X+Y})$.
The expectation of the distribution is the simple sum, $\mu_{X+Y} = \mu_X+\mu_Y$.
The S.D. of the distribution is not quite as simple since you need to know the covariance of the two distributions, but still straightforward to calculate: $\sigma_{X+Y}=\sqrt{\sigma_X^2 + \sigma_Y^2 + 2*\sigma_{XY}}$.
Now all we need is the covariance $\sigma_{XY}$, which is available in R using vcov() (for variance-covariance matrix) on most model objects.
set.seed(1)
x1 <- as.factor(c(rep("dog", 3), rep("cat", 3), rep("mouse", 3)))
x2 <- as.factor(rep(c("happy", "sad", "angry"), 3))
x3 <- rnorm(9, 0, 1) + runif(9, 3, 5)
y <- rnorm(9, 10, 2)
fit <- lm(formula = y ~ x1 + x2 + x3)
covariances <- vcov(fit)
(Intercept) x1dog x1mouse x2happy x2sad x3
(Intercept) 7.0133778 -0.67193955 -0.534382189 0.700431114 1.72549973 -1.801643527
x1dog -0.6719396 1.13299205 0.565017653 -0.022183489 -0.04014533 0.031569426
x1mouse -0.5343822 0.56501765 1.131288241 0.006502645 0.01176780 -0.009253944
x2happy 0.7004311 -0.02218349 0.006502645 1.395137989 1.04334118 -0.375713718
x2sad 1.7254997 -0.04014533 0.011767798 1.043341176 1.99575847 -0.679926841
x3 -1.8016435 0.03156943 -0.009253944 -0.375713718 -0.67992684 0.534679921
So the desired estimate for $\text{SE}_{happy,dog}$ would be sqrt(1.133 + 1.395 + 2*-0.022), or 1.576. | Measuring Standard Error of two or more coefficients combined | The sum of two correlated (jointly-)normal variables, $Z=X+Y$, is itself normal, $N(\mu_{X+Y},\sigma_{X+Y})$.
The expectation of the distribution is the simple sum, $\mu_{X+Y} = \mu_X+\mu_Y$.
The S.D. | Measuring Standard Error of two or more coefficients combined
The sum of two correlated (jointly-)normal variables, $Z=X+Y$, is itself normal, $N(\mu_{X+Y},\sigma_{X+Y})$.
The expectation of the distribution is the simple sum, $\mu_{X+Y} = \mu_X+\mu_Y$.
The S.D. of the distribution is not quite as simple since you need to know the covariance of the two distributions, but still straightforward to calculate: $\sigma_{X+Y}=\sqrt{\sigma_X^2 + \sigma_Y^2 + 2*\sigma_{XY}}$.
Now all we need is the covariance $\sigma_{XY}$, which is available in R using vcov() (for variance-covariance matrix) on most model objects.
set.seed(1)
x1 <- as.factor(c(rep("dog", 3), rep("cat", 3), rep("mouse", 3)))
x2 <- as.factor(rep(c("happy", "sad", "angry"), 3))
x3 <- rnorm(9, 0, 1) + runif(9, 3, 5)
y <- rnorm(9, 10, 2)
fit <- lm(formula = y ~ x1 + x2 + x3)
covariances <- vcov(fit)
(Intercept) x1dog x1mouse x2happy x2sad x3
(Intercept) 7.0133778 -0.67193955 -0.534382189 0.700431114 1.72549973 -1.801643527
x1dog -0.6719396 1.13299205 0.565017653 -0.022183489 -0.04014533 0.031569426
x1mouse -0.5343822 0.56501765 1.131288241 0.006502645 0.01176780 -0.009253944
x2happy 0.7004311 -0.02218349 0.006502645 1.395137989 1.04334118 -0.375713718
x2sad 1.7254997 -0.04014533 0.011767798 1.043341176 1.99575847 -0.679926841
x3 -1.8016435 0.03156943 -0.009253944 -0.375713718 -0.67992684 0.534679921
So the desired estimate for $\text{SE}_{happy,dog}$ would be sqrt(1.133 + 1.395 + 2*-0.022), or 1.576. | Measuring Standard Error of two or more coefficients combined
The sum of two correlated (jointly-)normal variables, $Z=X+Y$, is itself normal, $N(\mu_{X+Y},\sigma_{X+Y})$.
The expectation of the distribution is the simple sum, $\mu_{X+Y} = \mu_X+\mu_Y$.
The S.D. |
38,714 | Identifying the following distribution | For simulation purposes, a Weibull distribution may work well. Allow me to explain why and to say something about the limitations.
A plot of the original (unexponentiated) residuals immediately suggested a Weibull distribution to me. (One reason this family comes to mind is that it includes Rayleigh distributions, which are Weibull with shape parameter $2.$) The formula will depend on three parameters: a shape parameter plus a scale and location. A standard exploratory technique to test such a distributional hypothesis is the (quantile-quantile) probability plot: one draws a scatterplot of quantiles of the data against the same quantiles of a reference distribution. When this scatterplot is nearly linear, the data differ from the reference distribution only by a change of units--the scaling and recentering.
One exploratory way to find a good shape parameter is to adjust it until the probability plot looks as linear as possible. To avoid too much work, I used various approaches: only data from the first spectrum (optimal shape is $6.3$); equally spaced centiles of all data (optimum is $5.63$); and a variance-weighted version of the latter (optimum is $4.99$). There's little to choose from among those (they all fit the data pretty well). Taking the middle value produces the probability plot at the left:
The probability plot is exceptionally straight throughout its range, indicating a good fit.
The middle plot shows the corresponding Weibull frequency graph superimposed on the histogram. It tracks the peaks of the bars well, also suggesting a good fit. However, the corresponding chi-squared test indicates a little lack of fit ($\chi^2=334.6,$ $p=2\times 10^{-15}$ with $154$ degrees of freedom based on length-$0.1$ bins from $-8.5$ to $7.0$). To analyze the lack of fit I created a "rootogram" as invented by John Tukey. This displays the square roots of the histogram densities relative to the fitted distribution, thereby greatly magnifying the deviations of the data distribution above and below the fit. This is the right plot in the figure.
To interpret the rootogram, bear in mind that the square root of a count will, on average, be less than one unit from its expected value. You can see that's the case with most of the bars in the rootogram, confirming the previous good fits. In this plot, however, it is apparent that relative to the Weibull fit, the data are a little more numerous at the extremes and the center (the red positive bars) compared to the middle values (the blue negative bars), and this is a systematic, nearly symmetric pattern.
In this sense the Weibull description is not entirely adequate: we should not conclude there is some underlying physical law to explain a Weibull distribution of residuals. The Weibull shape is merely a mathematical convenience that succinctly describes these data very well. (There are other issues, such as the possibility of serial correlation of the residuals within each spectrum. There is some correlation, but it extends only for a couple of lags and therefore is unlikely to suggest any meaningful modification of the foregoing description.)
Ultimately, then, whether you use a Weibull distribution to simulate residuals (which you can exponentiate if you wish) depends on whether these small but systematic departures are important to capture in the simulation.
For the record, the Weibull distribution shown here has shape parameter $5.63,$ scale parameter $11.85,$ and is shifted by $-10.95.$ Because Weibull distributions are just power transformations of Exponential (that is, Gamma$(1)$) distributions, and Exponential random variates are easily obtained as the negative logarithms of the Uniform$(0,1)$ variates supplied by standard pseudorandom number generators in computing systems, it is easy and computationally cheap to generate Weibull variates. Specifically, letting $U$ have this Uniform distribution, simulate the (raw) residuals as
$$X = (-\log(U))^{1/5.63} * 11.85 - 10.95.$$
To illustrate this process, and to serve as a reference for interpreting the preceding data plots, I created a random sample in this manner of the same size as the original dataset ($801\times 64$ values) and drew its histogram, the same Weibull frequency curve, and the corresponding rootogram.
The typical bar is between 0 and 1 in height--but this time, the bar heights appear to vary randomly and independently, rather than following the systematic pattern in the data rootogram. | Identifying the following distribution | For simulation purposes, a Weibull distribution may work well. Allow me to explain why and to say something about the limitations.
A plot of the original (unexponentiated) residuals immediately sugge | Identifying the following distribution
For simulation purposes, a Weibull distribution may work well. Allow me to explain why and to say something about the limitations.
A plot of the original (unexponentiated) residuals immediately suggested a Weibull distribution to me. (One reason this family comes to mind is that it includes Rayleigh distributions, which are Weibull with shape parameter $2.$) The formula will depend on three parameters: a shape parameter plus a scale and location. A standard exploratory technique to test such a distributional hypothesis is the (quantile-quantile) probability plot: one draws a scatterplot of quantiles of the data against the same quantiles of a reference distribution. When this scatterplot is nearly linear, the data differ from the reference distribution only by a change of units--the scaling and recentering.
One exploratory way to find a good shape parameter is to adjust it until the probability plot looks as linear as possible. To avoid too much work, I used various approaches: only data from the first spectrum (optimal shape is $6.3$); equally spaced centiles of all data (optimum is $5.63$); and a variance-weighted version of the latter (optimum is $4.99$). There's little to choose from among those (they all fit the data pretty well). Taking the middle value produces the probability plot at the left:
The probability plot is exceptionally straight throughout its range, indicating a good fit.
The middle plot shows the corresponding Weibull frequency graph superimposed on the histogram. It tracks the peaks of the bars well, also suggesting a good fit. However, the corresponding chi-squared test indicates a little lack of fit ($\chi^2=334.6,$ $p=2\times 10^{-15}$ with $154$ degrees of freedom based on length-$0.1$ bins from $-8.5$ to $7.0$). To analyze the lack of fit I created a "rootogram" as invented by John Tukey. This displays the square roots of the histogram densities relative to the fitted distribution, thereby greatly magnifying the deviations of the data distribution above and below the fit. This is the right plot in the figure.
To interpret the rootogram, bear in mind that the square root of a count will, on average, be less than one unit from its expected value. You can see that's the case with most of the bars in the rootogram, confirming the previous good fits. In this plot, however, it is apparent that relative to the Weibull fit, the data are a little more numerous at the extremes and the center (the red positive bars) compared to the middle values (the blue negative bars), and this is a systematic, nearly symmetric pattern.
In this sense the Weibull description is not entirely adequate: we should not conclude there is some underlying physical law to explain a Weibull distribution of residuals. The Weibull shape is merely a mathematical convenience that succinctly describes these data very well. (There are other issues, such as the possibility of serial correlation of the residuals within each spectrum. There is some correlation, but it extends only for a couple of lags and therefore is unlikely to suggest any meaningful modification of the foregoing description.)
Ultimately, then, whether you use a Weibull distribution to simulate residuals (which you can exponentiate if you wish) depends on whether these small but systematic departures are important to capture in the simulation.
For the record, the Weibull distribution shown here has shape parameter $5.63,$ scale parameter $11.85,$ and is shifted by $-10.95.$ Because Weibull distributions are just power transformations of Exponential (that is, Gamma$(1)$) distributions, and Exponential random variates are easily obtained as the negative logarithms of the Uniform$(0,1)$ variates supplied by standard pseudorandom number generators in computing systems, it is easy and computationally cheap to generate Weibull variates. Specifically, letting $U$ have this Uniform distribution, simulate the (raw) residuals as
$$X = (-\log(U))^{1/5.63} * 11.85 - 10.95.$$
To illustrate this process, and to serve as a reference for interpreting the preceding data plots, I created a random sample in this manner of the same size as the original dataset ($801\times 64$ values) and drew its histogram, the same Weibull frequency curve, and the corresponding rootogram.
The typical bar is between 0 and 1 in height--but this time, the bar heights appear to vary randomly and independently, rather than following the systematic pattern in the data rootogram. | Identifying the following distribution
For simulation purposes, a Weibull distribution may work well. Allow me to explain why and to say something about the limitations.
A plot of the original (unexponentiated) residuals immediately sugge |
38,715 | Identifying the following distribution | I just did a hand-fit, but Weibull looks better than your Rayleigh. | Identifying the following distribution | I just did a hand-fit, but Weibull looks better than your Rayleigh. | Identifying the following distribution
I just did a hand-fit, but Weibull looks better than your Rayleigh. | Identifying the following distribution
I just did a hand-fit, but Weibull looks better than your Rayleigh. |
38,716 | Why is the intercept typed in as a 1 in stats packages (R, python) | It is logical, once you consider the matrix notation that your formula will be translated into internally. In the matrix, the non-constant predictors will be translated into (one or more) columns, and the intercept will be translated into a column consisting entirely of ones.
For instance, in R you would write a very simple OLS as:
lm(z~1+x+y)
In matrix notation, this would be translated into a model
$$ \begin{pmatrix} z_1 \\ z_2 \\ \vdots \\ z_n \end{pmatrix} =
\begin{pmatrix} 1 & x_1 & y_1 \\ 1 & x_2 & y_2 \\ \vdots & \vdots & \vdots \\ 1 & x_n & y_n \end{pmatrix}
\begin{pmatrix} \beta_0 \\ \beta_x \\ \beta_z \end{pmatrix}
+\begin{pmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots \\ \epsilon_n \end{pmatrix},
$$
and now you see where the $1$ comes from.
Actually, you could leave the 1+ out, since R will always presume you want to include an intercept, so this is completely equivalent to
lm(z~x+y).
However, if you want to suppress the intercept, you would write something like
lm(z~x+y-1),
which would be translated into a matrix without a 1 column:
$$ \begin{pmatrix} z_1 \\ z_2 \\ \vdots \\ z_n \end{pmatrix} =
\begin{pmatrix} x_1 & y_1 \\ x_2 & y_2 \\ \vdots & \vdots \\ x_n & y_n \end{pmatrix}
\begin{pmatrix} \beta_x \\ \beta_z \end{pmatrix}
+\begin{pmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots \\ \epsilon_n \end{pmatrix},
$$ | Why is the intercept typed in as a 1 in stats packages (R, python) | It is logical, once you consider the matrix notation that your formula will be translated into internally. In the matrix, the non-constant predictors will be translated into (one or more) columns, and | Why is the intercept typed in as a 1 in stats packages (R, python)
It is logical, once you consider the matrix notation that your formula will be translated into internally. In the matrix, the non-constant predictors will be translated into (one or more) columns, and the intercept will be translated into a column consisting entirely of ones.
For instance, in R you would write a very simple OLS as:
lm(z~1+x+y)
In matrix notation, this would be translated into a model
$$ \begin{pmatrix} z_1 \\ z_2 \\ \vdots \\ z_n \end{pmatrix} =
\begin{pmatrix} 1 & x_1 & y_1 \\ 1 & x_2 & y_2 \\ \vdots & \vdots & \vdots \\ 1 & x_n & y_n \end{pmatrix}
\begin{pmatrix} \beta_0 \\ \beta_x \\ \beta_z \end{pmatrix}
+\begin{pmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots \\ \epsilon_n \end{pmatrix},
$$
and now you see where the $1$ comes from.
Actually, you could leave the 1+ out, since R will always presume you want to include an intercept, so this is completely equivalent to
lm(z~x+y).
However, if you want to suppress the intercept, you would write something like
lm(z~x+y-1),
which would be translated into a matrix without a 1 column:
$$ \begin{pmatrix} z_1 \\ z_2 \\ \vdots \\ z_n \end{pmatrix} =
\begin{pmatrix} x_1 & y_1 \\ x_2 & y_2 \\ \vdots & \vdots \\ x_n & y_n \end{pmatrix}
\begin{pmatrix} \beta_x \\ \beta_z \end{pmatrix}
+\begin{pmatrix} \epsilon_1 \\ \epsilon_2 \\ \vdots \\ \epsilon_n \end{pmatrix},
$$ | Why is the intercept typed in as a 1 in stats packages (R, python)
It is logical, once you consider the matrix notation that your formula will be translated into internally. In the matrix, the non-constant predictors will be translated into (one or more) columns, and |
38,717 | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$ | Firstly I would suggest you read an excellent book by Ben Bolker entitled Ecological Models and Data in R. Written for ecologists , I think this is one of the best books on practical data analysis regardless of background, I'm an engineer and I have used it a lot. I'm sure there are other mathematical statistics book, however this book is by far the most practical book that I have read. He also has a package BBMLE which you might want to check.
The book unlike any other goes in to maximum likelihood estimation, profile likelihood and confidence interval estimation and all that.
Coming back to your problem, you need to write a log-likelihood of the function that you are trying to fit the data. Obviously you are assuming the error to be normally distributed as in the simulation, so the Log likelihood is:
$Log\ Likelihood (Lambda,sd) = -\frac{n}{2} log(sd) - \frac{n}{2} log(2\pi)- \frac{(y-x^{Lambda})^2}{2sd} $
You need to maximize the above equation using an optimization routine such as optim in R. Use the Hessian matrix from the optimization to assess the uncertainty of your estimated log likelihood function i.e., how steep or how flat the curvature of your function is at the optimal point. If the function is steep which implies less uncertainties at optimal point you would have a tighter confidence band on your parameter estimates, on the other hand if its flat you would have a wider confidence interval. Hessian, Fisher Information matrix would help you calculate the standard error and confidence interval.
Here is how you do it in R:
set.seed(8345)
Lambda = 1/2.42
x = rbeta(1e4, shape1=2,shape2=2)
y = x^Lambda + rnorm(1e4,mean = 0, sd=.1)
plot(x,y)
## Write Log Likelihood function
log.lik <- function(theta,y,x){
Lam <- theta[1]
sigma2 <- theta[2]
# sample size
n <- length(y)
#error
e<-y-(x^Lam)
#log likelihood
logl<- -.5*n*log(2*pi)-.5*n*log(sigma2)-((t(e)%*%e)/(2*sigma2))
return(-logl) # R optim does minimize so to maximize multiply by -1
}
## Estimate Paramters thru maximum likelihood
max.lik <- optim(c(1,1), fn=log.lik, method = "L-BFGS-B", lower = c(0.00001,0.00001), hessian = T,y=y,x=x)
# Lambda
Lam <- max.lik$par[1]
#0.4107119
#Fisher Information MAtrix
fisher_info<-solve(max.lik$hessian)
prop_sigma<-sqrt(diag(fisher_info))
## Estimate 95% Confidence Interval
upper<-max.lik$par+1.96*prop_sigma
lower<-max.lik$par-1.96*prop_sigma
interval<-data.frame(Parameter = c("Lambda","sd"),value=max.lik$par, lower=lower, upper=upper)
interval | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$ | Firstly I would suggest you read an excellent book by Ben Bolker entitled Ecological Models and Data in R. Written for ecologists , I think this is one of the best books on practical data analysis reg | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$
Firstly I would suggest you read an excellent book by Ben Bolker entitled Ecological Models and Data in R. Written for ecologists , I think this is one of the best books on practical data analysis regardless of background, I'm an engineer and I have used it a lot. I'm sure there are other mathematical statistics book, however this book is by far the most practical book that I have read. He also has a package BBMLE which you might want to check.
The book unlike any other goes in to maximum likelihood estimation, profile likelihood and confidence interval estimation and all that.
Coming back to your problem, you need to write a log-likelihood of the function that you are trying to fit the data. Obviously you are assuming the error to be normally distributed as in the simulation, so the Log likelihood is:
$Log\ Likelihood (Lambda,sd) = -\frac{n}{2} log(sd) - \frac{n}{2} log(2\pi)- \frac{(y-x^{Lambda})^2}{2sd} $
You need to maximize the above equation using an optimization routine such as optim in R. Use the Hessian matrix from the optimization to assess the uncertainty of your estimated log likelihood function i.e., how steep or how flat the curvature of your function is at the optimal point. If the function is steep which implies less uncertainties at optimal point you would have a tighter confidence band on your parameter estimates, on the other hand if its flat you would have a wider confidence interval. Hessian, Fisher Information matrix would help you calculate the standard error and confidence interval.
Here is how you do it in R:
set.seed(8345)
Lambda = 1/2.42
x = rbeta(1e4, shape1=2,shape2=2)
y = x^Lambda + rnorm(1e4,mean = 0, sd=.1)
plot(x,y)
## Write Log Likelihood function
log.lik <- function(theta,y,x){
Lam <- theta[1]
sigma2 <- theta[2]
# sample size
n <- length(y)
#error
e<-y-(x^Lam)
#log likelihood
logl<- -.5*n*log(2*pi)-.5*n*log(sigma2)-((t(e)%*%e)/(2*sigma2))
return(-logl) # R optim does minimize so to maximize multiply by -1
}
## Estimate Paramters thru maximum likelihood
max.lik <- optim(c(1,1), fn=log.lik, method = "L-BFGS-B", lower = c(0.00001,0.00001), hessian = T,y=y,x=x)
# Lambda
Lam <- max.lik$par[1]
#0.4107119
#Fisher Information MAtrix
fisher_info<-solve(max.lik$hessian)
prop_sigma<-sqrt(diag(fisher_info))
## Estimate 95% Confidence Interval
upper<-max.lik$par+1.96*prop_sigma
lower<-max.lik$par-1.96*prop_sigma
interval<-data.frame(Parameter = c("Lambda","sd"),value=max.lik$par, lower=lower, upper=upper)
interval | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$
Firstly I would suggest you read an excellent book by Ben Bolker entitled Ecological Models and Data in R. Written for ecologists , I think this is one of the best books on practical data analysis reg |
38,718 | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$ | Is there any standard way to do it?
If you think that following is a good approximation (the model you simulate from as an example)
$$y_i = x_i^\lambda +\epsilon_i, \qquad \epsilon_i\sim N(0,\sigma^2)$$
i.e.,
$$\log(E(y_i))=\lambda \log x_i$$
then you can use glm with family = gaussian("log") which is exactly this model
lambda <- 1/2.42
set.seed(49564503)
n <- 1e4
x <- rbeta(n, shape1 = 2,shape2 = 2)
y <- x^lambda + rnorm(n, sd = .1)
fit <- glm(y ~ log(x) - 1, family = gaussian("log"), start = c(0, 1))
summary(fit)
#R
#R Call:
#R glm(formula = y ~ log(x) - 1, family = gaussian("log"), start = 1)
#R
#R Deviance Residuals:
#R Min 1Q Median 3Q Max
#R -0.42452 -0.06767 0.00090 0.07020 0.34418
#R
#R Coefficients:
#R Estimate Std. Error t value Pr(>|t|)
#R log(x) 0.410666 0.001807 227.3 <2e-16 ***
#R ---
#R Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#R
#R (Dispersion parameter for gaussian family taken to be 0.01033428)
#R
#R Null deviance: 1057.81 on 10000 degrees of freedom
#R Residual deviance: 103.33 on 9999 degrees of freedom
#R AIC: -17341
#R
#R Number of Fisher Scoring iterations: 5
Notice that both the dispersion parameter and coefficient estimate match as expected. Now, you can make confidence interval with the standard error above or by using confint. | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$ | Is there any standard way to do it?
If you think that following is a good approximation (the model you simulate from as an example)
$$y_i = x_i^\lambda +\epsilon_i, \qquad \epsilon_i\sim N(0,\sigma^2 | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$
Is there any standard way to do it?
If you think that following is a good approximation (the model you simulate from as an example)
$$y_i = x_i^\lambda +\epsilon_i, \qquad \epsilon_i\sim N(0,\sigma^2)$$
i.e.,
$$\log(E(y_i))=\lambda \log x_i$$
then you can use glm with family = gaussian("log") which is exactly this model
lambda <- 1/2.42
set.seed(49564503)
n <- 1e4
x <- rbeta(n, shape1 = 2,shape2 = 2)
y <- x^lambda + rnorm(n, sd = .1)
fit <- glm(y ~ log(x) - 1, family = gaussian("log"), start = c(0, 1))
summary(fit)
#R
#R Call:
#R glm(formula = y ~ log(x) - 1, family = gaussian("log"), start = 1)
#R
#R Deviance Residuals:
#R Min 1Q Median 3Q Max
#R -0.42452 -0.06767 0.00090 0.07020 0.34418
#R
#R Coefficients:
#R Estimate Std. Error t value Pr(>|t|)
#R log(x) 0.410666 0.001807 227.3 <2e-16 ***
#R ---
#R Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#R
#R (Dispersion parameter for gaussian family taken to be 0.01033428)
#R
#R Null deviance: 1057.81 on 10000 degrees of freedom
#R Residual deviance: 103.33 on 9999 degrees of freedom
#R AIC: -17341
#R
#R Number of Fisher Scoring iterations: 5
Notice that both the dispersion parameter and coefficient estimate match as expected. Now, you can make confidence interval with the standard error above or by using confint. | Estimate $\lambda$ in the fitting line $x^\lambda$, where $x \in [0, 1]$
Is there any standard way to do it?
If you think that following is a good approximation (the model you simulate from as an example)
$$y_i = x_i^\lambda +\epsilon_i, \qquad \epsilon_i\sim N(0,\sigma^2 |
38,719 | What is the precise definition of "performance" in machine learning? | In the absence of any specific clarifying context, "performance" is just a synonym for "quality."
The sentence "I want a model that performs better" is essentially the same as the sentence "I want a higher-quality model." Readers understand that the speaker is not satisfied with how well the model solves some particular problem, but the reader does not know, precisely, what about the model is dissatisfactory. Does the model predict too many false positives? Or false negatives? Does it predict incorrect classes for images that have a tilted horizon, or are taken on cloudy days? Understanding what about the model needs improvement would require further, specific elaboration.
Likewise, if someone says that Adam has better performance than another optimizer, they're making a claim that Adam does better at some task, which they would have to specify for it to be possible to assess the truthfulness of the claim. One way to assesses performance of an optimizer is how many iterations it takes to reach some neighborhood around a minimum; another, which is particular to machine learning classifiers, is how well the solutions obtained by an optimizer generalize to out-of-sample data. | What is the precise definition of "performance" in machine learning? | In the absence of any specific clarifying context, "performance" is just a synonym for "quality."
The sentence "I want a model that performs better" is essentially the same as the sentence "I want a h | What is the precise definition of "performance" in machine learning?
In the absence of any specific clarifying context, "performance" is just a synonym for "quality."
The sentence "I want a model that performs better" is essentially the same as the sentence "I want a higher-quality model." Readers understand that the speaker is not satisfied with how well the model solves some particular problem, but the reader does not know, precisely, what about the model is dissatisfactory. Does the model predict too many false positives? Or false negatives? Does it predict incorrect classes for images that have a tilted horizon, or are taken on cloudy days? Understanding what about the model needs improvement would require further, specific elaboration.
Likewise, if someone says that Adam has better performance than another optimizer, they're making a claim that Adam does better at some task, which they would have to specify for it to be possible to assess the truthfulness of the claim. One way to assesses performance of an optimizer is how many iterations it takes to reach some neighborhood around a minimum; another, which is particular to machine learning classifiers, is how well the solutions obtained by an optimizer generalize to out-of-sample data. | What is the precise definition of "performance" in machine learning?
In the absence of any specific clarifying context, "performance" is just a synonym for "quality."
The sentence "I want a model that performs better" is essentially the same as the sentence "I want a h |
38,720 | What is the precise definition of "performance" in machine learning? | Performance does not englobe a formal definition, it is mostly dependent on, but not limited to:
the context of the model you are trying to implement
the metrics you are using to evaluate the model's output
the objective you are pursuing
The use of one metric or another will depend whether you are trying to predict a continuous or a discrete variable. Some of these are: Accuracy, Recall, Precision, R2, F-Measure, Mean Square Error, etc.
To make this clear, say for instance you are working on a credit card fraud machine learning algorithm, where you want to predict the number of fraud transactions. To evaluate how well the algorithm works: a) understand the context b) understand the metrics that are applicable to the problem
a) We are dealing with a classification problem; a transaction can be fraud or not (target is a discrete variable). We will be most-likely facing a highly imbalanced dataset since most of the credit card transactions are non-fraudulent.
b) Since it is a classification problem, we can discard all the metrics associated to continuous variables (for example, R2 and MSE). Moreover, due to the possible imbalance, we can also discard Accuracy metric. This leaves us with two metrics: Recall and Precision. We know by theory that these two metrics present a trade-off (if I increase one, the other decreases). Recall would help detect the major possible transactions that were fraud. Precision would help with avoiding misclassifying frauds.
Concluding, how well our it works, after considering the previous things, will ultimately depend on what is our objective:
Is our goal to detect the highest amount of fraudulent transactions
as possible? If it is, our metric to evaluate the model's
performance, and further improvements, will be Recall.
Is our goal to avoid classifying a transaction as non-fraud when it
was a fraud? If it is, our metric to evaluate the model's
performance, and further improvements, will be Precision.
Hopefully this provides you a better insight. | What is the precise definition of "performance" in machine learning? | Performance does not englobe a formal definition, it is mostly dependent on, but not limited to:
the context of the model you are trying to implement
the metrics you are using to evaluate the model' | What is the precise definition of "performance" in machine learning?
Performance does not englobe a formal definition, it is mostly dependent on, but not limited to:
the context of the model you are trying to implement
the metrics you are using to evaluate the model's output
the objective you are pursuing
The use of one metric or another will depend whether you are trying to predict a continuous or a discrete variable. Some of these are: Accuracy, Recall, Precision, R2, F-Measure, Mean Square Error, etc.
To make this clear, say for instance you are working on a credit card fraud machine learning algorithm, where you want to predict the number of fraud transactions. To evaluate how well the algorithm works: a) understand the context b) understand the metrics that are applicable to the problem
a) We are dealing with a classification problem; a transaction can be fraud or not (target is a discrete variable). We will be most-likely facing a highly imbalanced dataset since most of the credit card transactions are non-fraudulent.
b) Since it is a classification problem, we can discard all the metrics associated to continuous variables (for example, R2 and MSE). Moreover, due to the possible imbalance, we can also discard Accuracy metric. This leaves us with two metrics: Recall and Precision. We know by theory that these two metrics present a trade-off (if I increase one, the other decreases). Recall would help detect the major possible transactions that were fraud. Precision would help with avoiding misclassifying frauds.
Concluding, how well our it works, after considering the previous things, will ultimately depend on what is our objective:
Is our goal to detect the highest amount of fraudulent transactions
as possible? If it is, our metric to evaluate the model's
performance, and further improvements, will be Recall.
Is our goal to avoid classifying a transaction as non-fraud when it
was a fraud? If it is, our metric to evaluate the model's
performance, and further improvements, will be Precision.
Hopefully this provides you a better insight. | What is the precise definition of "performance" in machine learning?
Performance does not englobe a formal definition, it is mostly dependent on, but not limited to:
the context of the model you are trying to implement
the metrics you are using to evaluate the model' |
38,721 | What is the precise definition of "performance" in machine learning? | As the other answer correctly points out, there is no universal definition or measurement of performance of a machine learning model. Rather, performance metrics are highly dependent on the domain and ultimate purpose of the model being built. Performance of an ML model is just "how good" it does at a particular task, but the definition of "good" can take many forms. A "good" model could be one that predicts well, one that trains quickly, one that finds a robust solution, or any combination of the above.
For example, an algorithm used for a medical screening test should be highly sensitive - we want to catch all possible cases of a disease, at the cost of misdiagnosing some people who aren't actually sick. These individuals can go on for further tests that may optimize other metrics like positive predictive value, indicating that a positive test result is likely a result of actually having the disease. Depending on the purpose of the test, we may want to put more weight on true positives/negatives at the cost of errors on the other side.
Performance can also be a function of the error measure used. Suppose your classifier outputs values on a continuous scale which are then thresholded for a binary classification. Do you care only if points are on the correct side of the boundary (accuracy measure)? Or do you care how badly you missed on the misclassified points (RMSE)? There is no universal best way to optimize performance. | What is the precise definition of "performance" in machine learning? | As the other answer correctly points out, there is no universal definition or measurement of performance of a machine learning model. Rather, performance metrics are highly dependent on the domain and | What is the precise definition of "performance" in machine learning?
As the other answer correctly points out, there is no universal definition or measurement of performance of a machine learning model. Rather, performance metrics are highly dependent on the domain and ultimate purpose of the model being built. Performance of an ML model is just "how good" it does at a particular task, but the definition of "good" can take many forms. A "good" model could be one that predicts well, one that trains quickly, one that finds a robust solution, or any combination of the above.
For example, an algorithm used for a medical screening test should be highly sensitive - we want to catch all possible cases of a disease, at the cost of misdiagnosing some people who aren't actually sick. These individuals can go on for further tests that may optimize other metrics like positive predictive value, indicating that a positive test result is likely a result of actually having the disease. Depending on the purpose of the test, we may want to put more weight on true positives/negatives at the cost of errors on the other side.
Performance can also be a function of the error measure used. Suppose your classifier outputs values on a continuous scale which are then thresholded for a binary classification. Do you care only if points are on the correct side of the boundary (accuracy measure)? Or do you care how badly you missed on the misclassified points (RMSE)? There is no universal best way to optimize performance. | What is the precise definition of "performance" in machine learning?
As the other answer correctly points out, there is no universal definition or measurement of performance of a machine learning model. Rather, performance metrics are highly dependent on the domain and |
38,722 | Can "cross-validation" be used to choose a prior? | Since prior etymologically signifies before:
prior
adjective
existing or coming before in time, order, or importance.
"he has a prior engagement this evening"
synonyms: earlier, previous, preceding, foregoing, antecedent, advance, preparatory, preliminary, initial.
using the data to build the prior is not correct within a Bayesian perspective. It is found however in the "empirical Bayes" methodology, initiated by Robbins (1955) and defended by Efron, which uses first the data to estimate the parameters in a prior, like your Normal example, and a second time to run a pseudo-Bayesian analysis as if the prior was a true prior. Some versions of this approach enjoy convergence properties, for instance in semi- and non-parametric settings.
The question however seems to shy away from this solution by making a single use of the data and separating it into learning and inference parts. This is connected with the construction of intrinsic Bayes factors in the 1990's, by Jim Berger and co-authors, where a fraction of the data is used to make a flat (or otherwise improper) prior into a proper posterior, and use the remaining fraction to compute a Bayes factor (and run a test decision). In order to avoid the choice of the partition impacting the final result, all possible permutations are considered and one form of average (among arithmetic, geometric, harmonic, median) is computed. A much more elegant alternative is O'Hagan's (1995) fractional Bayes factor where the likelihood $L(\theta)$ is replaced with a fractional power $L^\alpha(\theta)$, which is used to create a posterior and this posterior is then used as a prior for the remainder of the likelihood $L^{1-\alpha}(\theta)$. The difficulty with these approaches is in determining the "right" amount of partitioning, e.g., the value of $\alpha$. | Can "cross-validation" be used to choose a prior? | Since prior etymologically signifies before:
prior
adjective
existing or coming before in time, order, or importance.
"he has a prior engagement this evening"
synonyms: earlier, previous, precedin | Can "cross-validation" be used to choose a prior?
Since prior etymologically signifies before:
prior
adjective
existing or coming before in time, order, or importance.
"he has a prior engagement this evening"
synonyms: earlier, previous, preceding, foregoing, antecedent, advance, preparatory, preliminary, initial.
using the data to build the prior is not correct within a Bayesian perspective. It is found however in the "empirical Bayes" methodology, initiated by Robbins (1955) and defended by Efron, which uses first the data to estimate the parameters in a prior, like your Normal example, and a second time to run a pseudo-Bayesian analysis as if the prior was a true prior. Some versions of this approach enjoy convergence properties, for instance in semi- and non-parametric settings.
The question however seems to shy away from this solution by making a single use of the data and separating it into learning and inference parts. This is connected with the construction of intrinsic Bayes factors in the 1990's, by Jim Berger and co-authors, where a fraction of the data is used to make a flat (or otherwise improper) prior into a proper posterior, and use the remaining fraction to compute a Bayes factor (and run a test decision). In order to avoid the choice of the partition impacting the final result, all possible permutations are considered and one form of average (among arithmetic, geometric, harmonic, median) is computed. A much more elegant alternative is O'Hagan's (1995) fractional Bayes factor where the likelihood $L(\theta)$ is replaced with a fractional power $L^\alpha(\theta)$, which is used to create a posterior and this posterior is then used as a prior for the remainder of the likelihood $L^{1-\alpha}(\theta)$. The difficulty with these approaches is in determining the "right" amount of partitioning, e.g., the value of $\alpha$. | Can "cross-validation" be used to choose a prior?
Since prior etymologically signifies before:
prior
adjective
existing or coming before in time, order, or importance.
"he has a prior engagement this evening"
synonyms: earlier, previous, precedin |
38,723 | Can "cross-validation" be used to choose a prior? | In this paper Andrew Gelman used cross validation on a corpus of datasets to propose a weakly informative prior, intended for routine use. That seems a sensible approach!
Gelman, Andrew, et al. "A weakly informative default prior distribution for logistic and other regression models." The annals of applied statistics 2.4 (2008): 1360-1383. | Can "cross-validation" be used to choose a prior? | In this paper Andrew Gelman used cross validation on a corpus of datasets to propose a weakly informative prior, intended for routine use. That seems a sensible approach!
Gelman, Andrew, et al. "A wea | Can "cross-validation" be used to choose a prior?
In this paper Andrew Gelman used cross validation on a corpus of datasets to propose a weakly informative prior, intended for routine use. That seems a sensible approach!
Gelman, Andrew, et al. "A weakly informative default prior distribution for logistic and other regression models." The annals of applied statistics 2.4 (2008): 1360-1383. | Can "cross-validation" be used to choose a prior?
In this paper Andrew Gelman used cross validation on a corpus of datasets to propose a weakly informative prior, intended for routine use. That seems a sensible approach!
Gelman, Andrew, et al. "A wea |
38,724 | Can "cross-validation" be used to choose a prior? | Firstly, I completely understand the temptation to do this. You want your model assumptions to be defensible and your model to be valid out-of-sample.
The issue is: this is not Bayesian inference. This is regularization using Bayes theorem. That isn't "good" or "bad." The answer to your titular question is yes absolutely. The only thing I would say is that there are probably better regularization methods that would be easier and equally valid under cross-validation.
Bayesian priors are not validated, they are solicited. A prior reflects your preexisting beliefs. If you have to validate it, you didn't believe it in the first place and therefore it is not a genuine prior in the true sense of the term.
The related technique of using secondary data sources to generate a prior that has been brought up is what is refereed to as "empirical" Bayes method, using a second separate date set to generate a prior. This works well for hierarchical models and for situations in which you have empirical prior knowledge you can call on.
I don't see how this makes sense if you are taking one data set and splitting it into two specifically for that purpose. It begs the question why not perform inference on the whole data set with a subjective prior? If you're going to infer your prior from a subset of the data using Bayesian inference, that requires a non-empirical prior which you could just use on the entire data set (in other words, you're just splitting Bayesian inference into two unnecessary steps). If you are not using Bayesian inference to generate a prior, then you don't really believe in using Bayesian inference to solve your given problem in the first place. In that case, just use the method you really believe in on the entire data set.
TLDR: if you don't have a prior belief you feel comfortable using, don't use Bayesian inference; just skip to the method you would use to generate the prior and use it across the board. | Can "cross-validation" be used to choose a prior? | Firstly, I completely understand the temptation to do this. You want your model assumptions to be defensible and your model to be valid out-of-sample.
The issue is: this is not Bayesian inference. Thi | Can "cross-validation" be used to choose a prior?
Firstly, I completely understand the temptation to do this. You want your model assumptions to be defensible and your model to be valid out-of-sample.
The issue is: this is not Bayesian inference. This is regularization using Bayes theorem. That isn't "good" or "bad." The answer to your titular question is yes absolutely. The only thing I would say is that there are probably better regularization methods that would be easier and equally valid under cross-validation.
Bayesian priors are not validated, they are solicited. A prior reflects your preexisting beliefs. If you have to validate it, you didn't believe it in the first place and therefore it is not a genuine prior in the true sense of the term.
The related technique of using secondary data sources to generate a prior that has been brought up is what is refereed to as "empirical" Bayes method, using a second separate date set to generate a prior. This works well for hierarchical models and for situations in which you have empirical prior knowledge you can call on.
I don't see how this makes sense if you are taking one data set and splitting it into two specifically for that purpose. It begs the question why not perform inference on the whole data set with a subjective prior? If you're going to infer your prior from a subset of the data using Bayesian inference, that requires a non-empirical prior which you could just use on the entire data set (in other words, you're just splitting Bayesian inference into two unnecessary steps). If you are not using Bayesian inference to generate a prior, then you don't really believe in using Bayesian inference to solve your given problem in the first place. In that case, just use the method you really believe in on the entire data set.
TLDR: if you don't have a prior belief you feel comfortable using, don't use Bayesian inference; just skip to the method you would use to generate the prior and use it across the board. | Can "cross-validation" be used to choose a prior?
Firstly, I completely understand the temptation to do this. You want your model assumptions to be defensible and your model to be valid out-of-sample.
The issue is: this is not Bayesian inference. Thi |
38,725 | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | Simultaneous modelling of mean and variance using double generalized linear models
The emphasis of gamlss is obviously on generalized additive models (GAMs). The general of idea of simultaneously modelling the mean and variance using generalized linear models (GLMs) rather than GAMs has been around much longer, and you might find the dglm package (Double GLMs) a simpler entry point for this sort of analysis.
I came up with the idea of double generalized linear models as part of my 1985 PhD thesis. In the normal case, the first publication with the same idea is Aitkin (1987).
For your example data we have:
> set.seed(1839)
> x <- runif(1000, 0, 100)
> y <- rnorm(1000, 0, x)
> library(dglm)
> fit <- dglm(y~x, dformula = ~x)
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~x)
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.3273 1.2319 -0.266 0.791
x -0.0336 0.0467 -0.719 0.472
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 1001 on 999 degrees of freedom
Scaled Residual Deviance: 1000 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 4.9319 0.08996 54.8 0.00e+00
x 0.0508 0.00157 32.4 7.99e-230
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2082 on 999 degrees of freedom
Scaled Residual Deviance: 1419 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10296
Number of Alternating Iterations: 6
You can see from the summary results that there is no significant trend for the means but a very highly significant increasing trend for the variances.
The dispersion coefficients are exactly twice the sigma coefficients returned by gamlss (in Stefan's answer) because dglm is modeling the variance rather than the standard deviation.
We can do even better by using $\log x$ as the predictor for the variance. You simulated the data to have sd($y_i$)$=\sigma_i=x_i$ so, on the log-scale, the true variance model is
$\log\sigma^2_i=2\log x_i$. We can fit this by:
> fit <- dglm(y~x, ~log(x))
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~log(x))
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.0189 0.0410 -0.461 0.645
x -0.0346 0.0323 -1.069 0.285
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 1001 on 999 degrees of freedom
Scaled Residual Deviance: 1000 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.0843 0.1694 0.498 0.619
log(x) 1.9850 0.0453 43.806 0.000
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2068 on 999 degrees of freedom
Scaled Residual Deviance: 1188 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10079
Number of Alternating Iterations: 4
You can see that the variance trend coefficient is estimated to be 1.985 when the true value is 2. The variance intercept is estimated to be 0.0843 when the true value is 0.
How it works
The basic idea is quite simple. We first fit a linear regression to the data:
> fit.m <- lm(y~x)
Then we extract the squared deviance residuals (aka unit deviances) from the fit and fit a log-linear chisquared glm to them:
> d <- residuals(fit.m)^2
> fit.d <- glm(d~x, family=Gamma(link="log"))
Then we take the fitted values from the variance (dispersion) model and use them as weights for the mean model:
> w <- 1/fitted(fit.d)
> fit.m <- lm(y~x, weights=w)
The dglm() function simply iterates this process to convergence.
It can be shown that this computes MLEs of all the parameters.
To examine the mean-model fit, you should use:
> summary(fit.m, dispersion=1)
The dispersion should be set to 1 because the variances have already been incorporated into the weights.
To examine the variance model, you should use
> summary(fit.d, dispersion=2)
The dispersion should be set to 2 because the unit deviances follow scaled chisquared distributions on 1 df, and chisquared on 1 df has squared coefficient of variation equal to 2.
The above example is for normal data, but the dglm() function works for any GLM family.
REML
The dglm package has the additional ability to use a REML method to return approximately unbiased variance estimators, unlike ML estimation which will return variance estimators that are systematically too small. For this data it makes little difference, because the number of mean parameters (2) is small compared to the number of observations (1000):
> fit <- dglm(y~x, ~x, method="reml")
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~x, method = "reml")
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.3297 1.2353 -0.267 0.790
x -0.0335 0.0467 -0.716 0.474
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 998 on 999 degrees of freedom
Scaled Residual Deviance: 997 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 4.9428 0.09029 54.7 0.00e+00
x 0.0507 0.00157 32.2 3.96e-227
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2082 on 999 degrees of freedom
Scaled Residual Deviance: 1419 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10296
Number of Alternating Iterations: 7
References
Aitkin, M. (1987). Modelling variance heterogeneity in normal regression using GLIM. Applied Statistics 36(3), 332-339.
Smyth, G. K. (1989). Generalized linear models with varying dispersion. J. R. Statist. Soc. B, 51, 47–60.
Smyth, G. K., and Verbyla, A. P. (1999). Adjusted likelihood methods for modelling dispersion in generalized linear models. Environmetrics, 10, 696-709. http://www.statsci.org/smyth/pubs/Ties98-Preprint.pdf
Smyth, G. K., and Verbyla, A. P. (1999). Double generalized linear models: approximate REML and diagnostics. In Statistical Modelling: Proceedings of the 14th International Workshop on Statistical Modelling, Graz, Austria, July 19-23, 1999, H. Friedl, A. Berghold, G. Kauermann (eds.), Technical University, Graz, Austria, pages 66-80. http://www.statsci.org/smyth/pubs/iwsm99-Preprint.pdf
Smyth, GK, and Verbyla, AP (2009). Leverage adjustments for dispersion modelling in generalized nonlinear models. Australian and New Zealand Journal of Statistics 51, 433-448. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | Simultaneous modelling of mean and variance using double generalized linear models
The emphasis of gamlss is obviously on generalized additive models (GAMs). The general of idea of simultaneously mode | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
Simultaneous modelling of mean and variance using double generalized linear models
The emphasis of gamlss is obviously on generalized additive models (GAMs). The general of idea of simultaneously modelling the mean and variance using generalized linear models (GLMs) rather than GAMs has been around much longer, and you might find the dglm package (Double GLMs) a simpler entry point for this sort of analysis.
I came up with the idea of double generalized linear models as part of my 1985 PhD thesis. In the normal case, the first publication with the same idea is Aitkin (1987).
For your example data we have:
> set.seed(1839)
> x <- runif(1000, 0, 100)
> y <- rnorm(1000, 0, x)
> library(dglm)
> fit <- dglm(y~x, dformula = ~x)
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~x)
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.3273 1.2319 -0.266 0.791
x -0.0336 0.0467 -0.719 0.472
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 1001 on 999 degrees of freedom
Scaled Residual Deviance: 1000 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 4.9319 0.08996 54.8 0.00e+00
x 0.0508 0.00157 32.4 7.99e-230
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2082 on 999 degrees of freedom
Scaled Residual Deviance: 1419 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10296
Number of Alternating Iterations: 6
You can see from the summary results that there is no significant trend for the means but a very highly significant increasing trend for the variances.
The dispersion coefficients are exactly twice the sigma coefficients returned by gamlss (in Stefan's answer) because dglm is modeling the variance rather than the standard deviation.
We can do even better by using $\log x$ as the predictor for the variance. You simulated the data to have sd($y_i$)$=\sigma_i=x_i$ so, on the log-scale, the true variance model is
$\log\sigma^2_i=2\log x_i$. We can fit this by:
> fit <- dglm(y~x, ~log(x))
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~log(x))
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.0189 0.0410 -0.461 0.645
x -0.0346 0.0323 -1.069 0.285
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 1001 on 999 degrees of freedom
Scaled Residual Deviance: 1000 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.0843 0.1694 0.498 0.619
log(x) 1.9850 0.0453 43.806 0.000
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2068 on 999 degrees of freedom
Scaled Residual Deviance: 1188 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10079
Number of Alternating Iterations: 4
You can see that the variance trend coefficient is estimated to be 1.985 when the true value is 2. The variance intercept is estimated to be 0.0843 when the true value is 0.
How it works
The basic idea is quite simple. We first fit a linear regression to the data:
> fit.m <- lm(y~x)
Then we extract the squared deviance residuals (aka unit deviances) from the fit and fit a log-linear chisquared glm to them:
> d <- residuals(fit.m)^2
> fit.d <- glm(d~x, family=Gamma(link="log"))
Then we take the fitted values from the variance (dispersion) model and use them as weights for the mean model:
> w <- 1/fitted(fit.d)
> fit.m <- lm(y~x, weights=w)
The dglm() function simply iterates this process to convergence.
It can be shown that this computes MLEs of all the parameters.
To examine the mean-model fit, you should use:
> summary(fit.m, dispersion=1)
The dispersion should be set to 1 because the variances have already been incorporated into the weights.
To examine the variance model, you should use
> summary(fit.d, dispersion=2)
The dispersion should be set to 2 because the unit deviances follow scaled chisquared distributions on 1 df, and chisquared on 1 df has squared coefficient of variation equal to 2.
The above example is for normal data, but the dglm() function works for any GLM family.
REML
The dglm package has the additional ability to use a REML method to return approximately unbiased variance estimators, unlike ML estimation which will return variance estimators that are systematically too small. For this data it makes little difference, because the number of mean parameters (2) is small compared to the number of observations (1000):
> fit <- dglm(y~x, ~x, method="reml")
> summary(fit)
Call: dglm(formula = y ~ x, dformula = ~x, method = "reml")
Mean Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.3297 1.2353 -0.267 0.790
x -0.0335 0.0467 -0.716 0.474
(Dispersion Parameters for gaussian family estimated as below )
Scaled Null Deviance: 998 on 999 degrees of freedom
Scaled Residual Deviance: 997 on 998 degrees of freedom
Dispersion Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 4.9428 0.09029 54.7 0.00e+00
x 0.0507 0.00157 32.2 3.96e-227
(Dispersion parameter for Gamma family taken to be 2 )
Scaled Null Deviance: 2082 on 999 degrees of freedom
Scaled Residual Deviance: 1419 on 998 degrees of freedom
Minus Twice the Log-Likelihood: 10296
Number of Alternating Iterations: 7
References
Aitkin, M. (1987). Modelling variance heterogeneity in normal regression using GLIM. Applied Statistics 36(3), 332-339.
Smyth, G. K. (1989). Generalized linear models with varying dispersion. J. R. Statist. Soc. B, 51, 47–60.
Smyth, G. K., and Verbyla, A. P. (1999). Adjusted likelihood methods for modelling dispersion in generalized linear models. Environmetrics, 10, 696-709. http://www.statsci.org/smyth/pubs/Ties98-Preprint.pdf
Smyth, G. K., and Verbyla, A. P. (1999). Double generalized linear models: approximate REML and diagnostics. In Statistical Modelling: Proceedings of the 14th International Workshop on Statistical Modelling, Graz, Austria, July 19-23, 1999, H. Friedl, A. Berghold, G. Kauermann (eds.), Technical University, Graz, Austria, pages 66-80. http://www.statsci.org/smyth/pubs/iwsm99-Preprint.pdf
Smyth, GK, and Verbyla, AP (2009). Leverage adjustments for dispersion modelling in generalized nonlinear models. Australian and New Zealand Journal of Statistics 51, 433-448. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
Simultaneous modelling of mean and variance using double generalized linear models
The emphasis of gamlss is obviously on generalized additive models (GAMs). The general of idea of simultaneously mode |
38,726 | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | If I understand you correctly, this can be done using the gamlss() function in the gamlss package.
Given your example, you can model the scale parameter $\sigma$ as follows:
fit <- gamlss(y~x, sigma.formula = ~x, data = dat, family = NO)
> summary(fit)
******************************************************************
Family: c("NO", "Normal")
Call: gamlss(formula = y ~ x, sigma.formula = ~x, family = NO, data = dat)
Fitting method: RS()
------------------------------------------------------------------
Mu link function: identity
Mu Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.32765 1.23130 -0.266 0.790
x -0.03359 0.04671 -0.719 0.472
------------------------------------------------------------------
Sigma link function: log
Sigma Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.4663263 0.0533045 46.27 <2e-16 ***
x 0.0254100 0.0009709 26.17 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
------------------------------------------------------------------
No. of observations in the fit: 1000
Degrees of Freedom for the fit: 4
Residual Deg. of Freedom: 996
at cycle: 3
Global Deviance: 10296.29
AIC: 10304.29
SBC: 10323.92
******************************************************************
See also Table 1 in the link above for all other available distributions. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | If I understand you correctly, this can be done using the gamlss() function in the gamlss package.
Given your example, you can model the scale parameter $\sigma$ as follows:
fit <- gamlss(y~x, sigma. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
If I understand you correctly, this can be done using the gamlss() function in the gamlss package.
Given your example, you can model the scale parameter $\sigma$ as follows:
fit <- gamlss(y~x, sigma.formula = ~x, data = dat, family = NO)
> summary(fit)
******************************************************************
Family: c("NO", "Normal")
Call: gamlss(formula = y ~ x, sigma.formula = ~x, family = NO, data = dat)
Fitting method: RS()
------------------------------------------------------------------
Mu link function: identity
Mu Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.32765 1.23130 -0.266 0.790
x -0.03359 0.04671 -0.719 0.472
------------------------------------------------------------------
Sigma link function: log
Sigma Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.4663263 0.0533045 46.27 <2e-16 ***
x 0.0254100 0.0009709 26.17 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
------------------------------------------------------------------
No. of observations in the fit: 1000
Degrees of Freedom for the fit: 4
Residual Deg. of Freedom: 996
at cycle: 3
Global Deviance: 10296.29
AIC: 10304.29
SBC: 10323.92
******************************************************************
See also Table 1 in the link above for all other available distributions. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
If I understand you correctly, this can be done using the gamlss() function in the gamlss package.
Given your example, you can model the scale parameter $\sigma$ as follows:
fit <- gamlss(y~x, sigma. |
38,727 | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | @Stefan gave rich family of models with the use of gamlss so my response here is more of an extended comment.
For some models with non-constant variance one can just do a simple "rearrangement" of the model and use simpler functions such as lm.
Suppose the model is
$$y=a+b x + x \epsilon$$
with $\epsilon \sim N(0,\sigma^2)$. We can just divide everything by $x$ and end up with a "standard" linear model with constant variance:
$${y \over x} = {a \over x} + b + \epsilon$$
We now have a typical linear model with $y/x$ as the dependent variable, $1/x$ is the independent variable with "slope" $a$ and intercept $b$ and the variance is constant. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors? | @Stefan gave rich family of models with the use of gamlss so my response here is more of an extended comment.
For some models with non-constant variance one can just do a simple "rearrangement" of the | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
@Stefan gave rich family of models with the use of gamlss so my response here is more of an extended comment.
For some models with non-constant variance one can just do a simple "rearrangement" of the model and use simpler functions such as lm.
Suppose the model is
$$y=a+b x + x \epsilon$$
with $\epsilon \sim N(0,\sigma^2)$. We can just divide everything by $x$ and end up with a "standard" linear model with constant variance:
$${y \over x} = {a \over x} + b + \epsilon$$
We now have a typical linear model with $y/x$ as the dependent variable, $1/x$ is the independent variable with "slope" $a$ and intercept $b$ and the variance is constant. | Conditionally heteroskedastic linear regression: How can I model variance from given predictors?
@Stefan gave rich family of models with the use of gamlss so my response here is more of an extended comment.
For some models with non-constant variance one can just do a simple "rearrangement" of the |
38,728 | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | To clarify terminology, a GLM with Gaussian distribution and identity link is identical to the general linear model or linear regression. So I will simply refer to it as linear regression going forward.
Additionally, the normality assumption in regression is on the error term. Since the residuals are estimated errors, we verify this assumption using the residuals or variants of the residuals, like studentized deleted residuals. Claiming the distributional assumption applies to the error term works in linear regression. However, for other GLMs like logistic regression, we do not assume the error term is binomial. A more general assumption for linear regression is that the data are normally distributed with a mean that depends on the predictors and a variance that is constant. Since the mean of the distribution depends on the predictors, to verify normality, we extract these means, hence giving all of the data the same center/location. This is what residuals are and then we can plot these residuals to check normality. Beyond linear regression, such empirical verification becomes more complicated.
It happens that the normality assumption in linear regression is one of the assumptions we do not need to care much about. The least squares coefficients do not depend on normality. However, classical inference using t-tests relies on the normality assumption. But from central limit theorem, we know this assumption does not matter too much once the sample sizes are large enough.
Rather than moving away from linear regression because of non-normality, I might move to another GLM if I could hypothesize a theoretical reason for why another distribution would be more appropriate. For example, if my data were count so non-negative and they were largely low counts with a few high values, I might start to consider a Poisson distribution. If the data were binary, then Binomial distribution is reasonable. The normal distribution is a reasonable choice if all we are willing to assume is that the data have finite variance and their range is $(-\infty, \infty)$. Usually, we can make more assumptions about the data than these two assumptions.
Additionally, the linear regression can handle multiple predictors predicting a single outcome. Wilcoxon/Spearman are for single predictor situations, so they are not comparable to linear regression in this way. They are directly comparable to specialized linear regressions like the Pearson correlation and the t test. However, they ask different questions of the data. Wilcoxon tests are stochastic dominance tests comparing two groups, while Spearman test is a measure of monotonic relation (like an ordinal linear correlation). So even when they are similar to linear regression, they ask different questions of the data.
Finally, with regard to your final question, modeling is hard. Model selection is a difficult problem. A reasonable approach is to attempt different models then observe their varying implications. If their implications are similar, that makes life easy. If they differ, that can be interesting for research purposes. With Bayesian modeling, we have a few more options in that we do not simply have to select a model, we can combine different models to account for our uncertainty in our final model.
Edit
An error on my part from the first paragraph: general linear model also includes MANOVA; this differentiates general linear model from the standard linear regression. All other members of the general linear model family are linear regression models or generalized linear models with gaussian distribution and identity link function. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | To clarify terminology, a GLM with Gaussian distribution and identity link is identical to the general linear model or linear regression. So I will simply refer to it as linear regression going forwar | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
To clarify terminology, a GLM with Gaussian distribution and identity link is identical to the general linear model or linear regression. So I will simply refer to it as linear regression going forward.
Additionally, the normality assumption in regression is on the error term. Since the residuals are estimated errors, we verify this assumption using the residuals or variants of the residuals, like studentized deleted residuals. Claiming the distributional assumption applies to the error term works in linear regression. However, for other GLMs like logistic regression, we do not assume the error term is binomial. A more general assumption for linear regression is that the data are normally distributed with a mean that depends on the predictors and a variance that is constant. Since the mean of the distribution depends on the predictors, to verify normality, we extract these means, hence giving all of the data the same center/location. This is what residuals are and then we can plot these residuals to check normality. Beyond linear regression, such empirical verification becomes more complicated.
It happens that the normality assumption in linear regression is one of the assumptions we do not need to care much about. The least squares coefficients do not depend on normality. However, classical inference using t-tests relies on the normality assumption. But from central limit theorem, we know this assumption does not matter too much once the sample sizes are large enough.
Rather than moving away from linear regression because of non-normality, I might move to another GLM if I could hypothesize a theoretical reason for why another distribution would be more appropriate. For example, if my data were count so non-negative and they were largely low counts with a few high values, I might start to consider a Poisson distribution. If the data were binary, then Binomial distribution is reasonable. The normal distribution is a reasonable choice if all we are willing to assume is that the data have finite variance and their range is $(-\infty, \infty)$. Usually, we can make more assumptions about the data than these two assumptions.
Additionally, the linear regression can handle multiple predictors predicting a single outcome. Wilcoxon/Spearman are for single predictor situations, so they are not comparable to linear regression in this way. They are directly comparable to specialized linear regressions like the Pearson correlation and the t test. However, they ask different questions of the data. Wilcoxon tests are stochastic dominance tests comparing two groups, while Spearman test is a measure of monotonic relation (like an ordinal linear correlation). So even when they are similar to linear regression, they ask different questions of the data.
Finally, with regard to your final question, modeling is hard. Model selection is a difficult problem. A reasonable approach is to attempt different models then observe their varying implications. If their implications are similar, that makes life easy. If they differ, that can be interesting for research purposes. With Bayesian modeling, we have a few more options in that we do not simply have to select a model, we can combine different models to account for our uncertainty in our final model.
Edit
An error on my part from the first paragraph: general linear model also includes MANOVA; this differentiates general linear model from the standard linear regression. All other members of the general linear model family are linear regression models or generalized linear models with gaussian distribution and identity link function. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
To clarify terminology, a GLM with Gaussian distribution and identity link is identical to the general linear model or linear regression. So I will simply refer to it as linear regression going forwar |
38,729 | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | The model that is a generalization of Wilcoxon, Kruskal-Wallis, and, to some extent, Spearman's $\rho$, is the proportional odds ordinal logistic semiparametric model. For short we call it the proportional odds (PO) model. The PO model handles the full generality of the linear model plus more, because it is invariant to how $Y$ is transformed. This circumvents the need to guess about whether residuals have a normal distribution. The PO model is robust with regard to $Y$ and is 0.95 as efficient as the linear model if normality holds. Otherwise it can be more efficient than the linear model.
Software needs to make it fast to handle the case where there is a large number $k$ of distinct $Y$ values, as the number of intercepts in the PO model is $k-1$. The R rms package orm function is fast for $k$ up to about 6000.
See my detailed case study in my RMS course notes for modeling continuous $Y$ using ordinal regression.
Once you are comfortable with ordinal response models, you no longer even need the special cases such as Wilcoxon. And ironically the PO model handles extreme ties better than the Wilcoxon test. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | The model that is a generalization of Wilcoxon, Kruskal-Wallis, and, to some extent, Spearman's $\rho$, is the proportional odds ordinal logistic semiparametric model. For short we call it the propor | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
The model that is a generalization of Wilcoxon, Kruskal-Wallis, and, to some extent, Spearman's $\rho$, is the proportional odds ordinal logistic semiparametric model. For short we call it the proportional odds (PO) model. The PO model handles the full generality of the linear model plus more, because it is invariant to how $Y$ is transformed. This circumvents the need to guess about whether residuals have a normal distribution. The PO model is robust with regard to $Y$ and is 0.95 as efficient as the linear model if normality holds. Otherwise it can be more efficient than the linear model.
Software needs to make it fast to handle the case where there is a large number $k$ of distinct $Y$ values, as the number of intercepts in the PO model is $k-1$. The R rms package orm function is fast for $k$ up to about 6000.
See my detailed case study in my RMS course notes for modeling continuous $Y$ using ordinal regression.
Once you are comfortable with ordinal response models, you no longer even need the special cases such as Wilcoxon. And ironically the PO model handles extreme ties better than the Wilcoxon test. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
The model that is a generalization of Wilcoxon, Kruskal-Wallis, and, to some extent, Spearman's $\rho$, is the proportional odds ordinal logistic semiparametric model. For short we call it the propor |
38,730 | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | I think Jim's answer addresses all your points adequately, but I'll try to boil it down to the per-question points.
1) Are these two approaches appropriate and equally valid alternatives, depending on (non)normality?
Definitely not. Regression, in general, seeks to describe the relationship between typical values of a random variable given known information. In their comment, whuber describes the (very different) purpose of the other two tests.
2) Even in case of non-normality, wouldn't a different GLM type be better than a combination of Wilcoxon rank sum tests and a Spearman’s rank correlation? (Not sure which type of GLM would be appropriate though, as the response is still continuous...gamma perhaps?)
Definitely so. We would need more information about the variable to provide specific guidance. Residual plots are a good way to convey the presumed lack of normality.
3) In a GLM framework, aren't we worried about non-normality of residuals, rather than raw data (which is not always the same thing)?
Correct. This is almost never the same thing. Residual plots are a good tool to explore this in linear regression. As Jim mentions, deviations from normality are not in and of themselves a great concern when you have a moderately sized sample and care only about the regression coefficients or mean predicted values.
On the other hand, a more important condition that residual plots also allow you to assess is a mean value of zero for the residuals. If the residuals stray too far at times, it suggests the model may be misspecified.
4) Doesn't a GLM (generalized linear model) with "normal distribution and identity link" simply mean a general linear model (i.e. an ordinary linear model)?
Not quite. A "general linear model" refers to a, well, general version of linear models. This generality also allows for multiple outcomes to be analyzed simultaneously. Generalized linear models only handle univariate outcomes. The normal-identity GLM could be described as "multiple linear regression". That makes it both a particular case of a GLM and of the general linear model.
5) Is this approach of using p-values from a full model (including all variables) appropriate, or would a variable selection (using AIC or similar) be more appropriate?
A p-value only allows you to say whether a statistically significant difference was observed, not that it wasn't, but it fails at communicating anything beyond that. I suggest using the confidence intervals to describe the findings provided by the model, as they show the range of plausible values for the estimated parameters. Even if a variable is significant, a wide confidence interval can suggest that little useful information about that particular relationship was gleaned. Conversely, a non-significant variable with a narrow confidence interval suggests that the presumed relationship is either absent or small in magnitude.
Using AIC for variable selection addresses a very different question. Selecting the AIC-best model will, on average, give you the model that makes the best predictions while also being as small as possible. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM? | I think Jim's answer addresses all your points adequately, but I'll try to boil it down to the per-question points.
1) Are these two approaches appropriate and equally valid alternatives, depending o | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
I think Jim's answer addresses all your points adequately, but I'll try to boil it down to the per-question points.
1) Are these two approaches appropriate and equally valid alternatives, depending on (non)normality?
Definitely not. Regression, in general, seeks to describe the relationship between typical values of a random variable given known information. In their comment, whuber describes the (very different) purpose of the other two tests.
2) Even in case of non-normality, wouldn't a different GLM type be better than a combination of Wilcoxon rank sum tests and a Spearman’s rank correlation? (Not sure which type of GLM would be appropriate though, as the response is still continuous...gamma perhaps?)
Definitely so. We would need more information about the variable to provide specific guidance. Residual plots are a good way to convey the presumed lack of normality.
3) In a GLM framework, aren't we worried about non-normality of residuals, rather than raw data (which is not always the same thing)?
Correct. This is almost never the same thing. Residual plots are a good tool to explore this in linear regression. As Jim mentions, deviations from normality are not in and of themselves a great concern when you have a moderately sized sample and care only about the regression coefficients or mean predicted values.
On the other hand, a more important condition that residual plots also allow you to assess is a mean value of zero for the residuals. If the residuals stray too far at times, it suggests the model may be misspecified.
4) Doesn't a GLM (generalized linear model) with "normal distribution and identity link" simply mean a general linear model (i.e. an ordinary linear model)?
Not quite. A "general linear model" refers to a, well, general version of linear models. This generality also allows for multiple outcomes to be analyzed simultaneously. Generalized linear models only handle univariate outcomes. The normal-identity GLM could be described as "multiple linear regression". That makes it both a particular case of a GLM and of the general linear model.
5) Is this approach of using p-values from a full model (including all variables) appropriate, or would a variable selection (using AIC or similar) be more appropriate?
A p-value only allows you to say whether a statistically significant difference was observed, not that it wasn't, but it fails at communicating anything beyond that. I suggest using the confidence intervals to describe the findings provided by the model, as they show the range of plausible values for the estimated parameters. Even if a variable is significant, a wide confidence interval can suggest that little useful information about that particular relationship was gleaned. Conversely, a non-significant variable with a narrow confidence interval suggests that the presumed relationship is either absent or small in magnitude.
Using AIC for variable selection addresses a very different question. Selecting the AIC-best model will, on average, give you the model that makes the best predictions while also being as small as possible. | Validity of using a combination of Wilcoxon tests and Spearman rho as an alternative to GLM?
I think Jim's answer addresses all your points adequately, but I'll try to boil it down to the per-question points.
1) Are these two approaches appropriate and equally valid alternatives, depending o |
38,731 | Reference book for logistic regression | Hosmer and Lemeshow's (later eds. also Sturdivant) Applied Logistic Regression
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582472.html
I cannot say that it is the best book though, because I have not read others on logistic regression. It think it is a standard work though. | Reference book for logistic regression | Hosmer and Lemeshow's (later eds. also Sturdivant) Applied Logistic Regression
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582472.html
I cannot say that it is the best book though, because I | Reference book for logistic regression
Hosmer and Lemeshow's (later eds. also Sturdivant) Applied Logistic Regression
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582472.html
I cannot say that it is the best book though, because I have not read others on logistic regression. It think it is a standard work though. | Reference book for logistic regression
Hosmer and Lemeshow's (later eds. also Sturdivant) Applied Logistic Regression
http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470582472.html
I cannot say that it is the best book though, because I |
38,732 | Reference book for logistic regression | Although it is not specifically on logistic regression, Agresti's Categorical Data Analysis is recommended. Chapters 4-6 cover "Introduction to Generalized Linear Models", "Logistic Regression", and "Building, Checking, and Applying Logistic Regression Models". Previous chapters could also provide some background about discrete distributions and statistical inference that might be helpful to understand models in the subsequent chapters. | Reference book for logistic regression | Although it is not specifically on logistic regression, Agresti's Categorical Data Analysis is recommended. Chapters 4-6 cover "Introduction to Generalized Linear Models", "Logistic Regression", and " | Reference book for logistic regression
Although it is not specifically on logistic regression, Agresti's Categorical Data Analysis is recommended. Chapters 4-6 cover "Introduction to Generalized Linear Models", "Logistic Regression", and "Building, Checking, and Applying Logistic Regression Models". Previous chapters could also provide some background about discrete distributions and statistical inference that might be helpful to understand models in the subsequent chapters. | Reference book for logistic regression
Although it is not specifically on logistic regression, Agresti's Categorical Data Analysis is recommended. Chapters 4-6 cover "Introduction to Generalized Linear Models", "Logistic Regression", and " |
38,733 | Reference book for logistic regression | Possibly even better than a book, I can highly recommend Andrew Ng's coursera course on machine learning. It gives an excellent overview of several machine learning algorithms. The main advantages are that it both discusses the theory and discusses many practical things to worry about when implementing machine learning algorithms. What really makes it better than a book for you in my opinion is that it has programming exercies in matlab for most of the algorithms, including if I remember correctly both regression and categorization using logistic regression. https://www.coursera.org/learn/machine-learning | Reference book for logistic regression | Possibly even better than a book, I can highly recommend Andrew Ng's coursera course on machine learning. It gives an excellent overview of several machine learning algorithms. The main advantages are | Reference book for logistic regression
Possibly even better than a book, I can highly recommend Andrew Ng's coursera course on machine learning. It gives an excellent overview of several machine learning algorithms. The main advantages are that it both discusses the theory and discusses many practical things to worry about when implementing machine learning algorithms. What really makes it better than a book for you in my opinion is that it has programming exercies in matlab for most of the algorithms, including if I remember correctly both regression and categorization using logistic regression. https://www.coursera.org/learn/machine-learning | Reference book for logistic regression
Possibly even better than a book, I can highly recommend Andrew Ng's coursera course on machine learning. It gives an excellent overview of several machine learning algorithms. The main advantages are |
38,734 | Probability of surviving an event three times | When you write "No extra variables, each incident is isolated and does not affect the subsequent", the mathematical word for this is that they are independent. And for independent events $A$ and $B$, the probability of both events occurring is $P(A) \times P(B)$. Moreover, if there are three independent events $A$, $B$ and $C$, then the probability of all three occurring is given by $P(A) \times P(B) \times P(C)$. If each event has probability $0.4$ then the probability you want will be $0.4^3=0.064=6.4\%$
For some intuition, imagine we start with one hundred people. (My approach of visualising probabilities by considering the possible outcomes of a large group of people is inspired by the work of the Winton programme for the public understanding of risk at Cambridge University, led by David Spiegelhalter. See e.g. this animation of risk of cancer.)
Then only $40\%$ survive the first incident. This leaves only forty people.
Then only $40\%$ of these survivors also survive the second incident. This leaves $40\%$ of forty which is sixteen people. The probability of one of the one hundred people surviving both the first and second incidents is clearly sixteen out of one hundred, i.e. $\frac{16}{100} = 0.16 = 16\%$.
Now can you see how this extends to the third incident?
Since the shaded fraction of the square's area represents the desired probability, it may help to dispense with the idea of one hundred imaginary people and just consider a square measuring one unit by one unit. If I slightly recolour the previous diagram and cut the sides into proportions of $0.4$ and $0.6$, rather than four and six people, we get this:
Perhaps this gives a geometric intuition for the multiplication of probabilities for two independent events.
Essentially we solve for probabilities of independent events the same way we solve any "find a proportion of a proportion" question: by multiplication. If you'd wanted to find $40\%$ of $40\%$, you would calculate $0.4 \times 0.4 = 0.16 = 16\%$. This is what we are doing, but with the proportions interpreted as independent probabilities. | Probability of surviving an event three times | When you write "No extra variables, each incident is isolated and does not affect the subsequent", the mathematical word for this is that they are independent. And for independent events $A$ and $B$, | Probability of surviving an event three times
When you write "No extra variables, each incident is isolated and does not affect the subsequent", the mathematical word for this is that they are independent. And for independent events $A$ and $B$, the probability of both events occurring is $P(A) \times P(B)$. Moreover, if there are three independent events $A$, $B$ and $C$, then the probability of all three occurring is given by $P(A) \times P(B) \times P(C)$. If each event has probability $0.4$ then the probability you want will be $0.4^3=0.064=6.4\%$
For some intuition, imagine we start with one hundred people. (My approach of visualising probabilities by considering the possible outcomes of a large group of people is inspired by the work of the Winton programme for the public understanding of risk at Cambridge University, led by David Spiegelhalter. See e.g. this animation of risk of cancer.)
Then only $40\%$ survive the first incident. This leaves only forty people.
Then only $40\%$ of these survivors also survive the second incident. This leaves $40\%$ of forty which is sixteen people. The probability of one of the one hundred people surviving both the first and second incidents is clearly sixteen out of one hundred, i.e. $\frac{16}{100} = 0.16 = 16\%$.
Now can you see how this extends to the third incident?
Since the shaded fraction of the square's area represents the desired probability, it may help to dispense with the idea of one hundred imaginary people and just consider a square measuring one unit by one unit. If I slightly recolour the previous diagram and cut the sides into proportions of $0.4$ and $0.6$, rather than four and six people, we get this:
Perhaps this gives a geometric intuition for the multiplication of probabilities for two independent events.
Essentially we solve for probabilities of independent events the same way we solve any "find a proportion of a proportion" question: by multiplication. If you'd wanted to find $40\%$ of $40\%$, you would calculate $0.4 \times 0.4 = 0.16 = 16\%$. This is what we are doing, but with the proportions interpreted as independent probabilities. | Probability of surviving an event three times
When you write "No extra variables, each incident is isolated and does not affect the subsequent", the mathematical word for this is that they are independent. And for independent events $A$ and $B$, |
38,735 | Invert a sparse covariance matrix | Could you make use of a simple block matrix inversion?
$$\left[\begin{array}{cc} A & B \\C & D \end{array}\right]^{-1}$$
$$=\begin{bmatrix}
(A - BD^{-1}C)^{-1} & -A^{-1}B(D - CA^{-1}B)^{-1} \\
-D^{-1}C(A - BD^{-1}C)^{-1} & (D - CA^{-1}B)^{-1}
\end{bmatrix}$$
(where here "$A$" would probably best correspond to your matrix with diagonal or block-diagonal $(A,B,C)$)
If your covariance is really an ordinary variance-covariance matrix, there are more suitable (but related) calculations. You might also consider some matrix decomposition, such as a Choleski, which would be greatly simplified by the particular structure you have.
--
usεr11852 makes an excellent point in comments; there are many situations where you don't really need to compute the inverse itself. | Invert a sparse covariance matrix | Could you make use of a simple block matrix inversion?
$$\left[\begin{array}{cc} A & B \\C & D \end{array}\right]^{-1}$$
$$=\begin{bmatrix}
(A - BD^{-1}C)^{-1} & -A^{-1}B(D - | Invert a sparse covariance matrix
Could you make use of a simple block matrix inversion?
$$\left[\begin{array}{cc} A & B \\C & D \end{array}\right]^{-1}$$
$$=\begin{bmatrix}
(A - BD^{-1}C)^{-1} & -A^{-1}B(D - CA^{-1}B)^{-1} \\
-D^{-1}C(A - BD^{-1}C)^{-1} & (D - CA^{-1}B)^{-1}
\end{bmatrix}$$
(where here "$A$" would probably best correspond to your matrix with diagonal or block-diagonal $(A,B,C)$)
If your covariance is really an ordinary variance-covariance matrix, there are more suitable (but related) calculations. You might also consider some matrix decomposition, such as a Choleski, which would be greatly simplified by the particular structure you have.
--
usεr11852 makes an excellent point in comments; there are many situations where you don't really need to compute the inverse itself. | Invert a sparse covariance matrix
Could you make use of a simple block matrix inversion?
$$\left[\begin{array}{cc} A & B \\C & D \end{array}\right]^{-1}$$
$$=\begin{bmatrix}
(A - BD^{-1}C)^{-1} & -A^{-1}B(D - |
38,736 | Invert a sparse covariance matrix | For general sparse matrices, very efficient Choleski-based inversion can be done using the SparseM package. The basic steps are to create a vector of nonzero elements and vectors of row and column numbers to which these elements correspond. SparseM takes it from there. I've used this in the R rms package orm function allowing handling of thousands of intercepts in an ordinal regression model. The method for obtaining the equivalent of $(X'X)^{-1}X'Y$ is incredibly fast. A separate inverse is not computed. | Invert a sparse covariance matrix | For general sparse matrices, very efficient Choleski-based inversion can be done using the SparseM package. The basic steps are to create a vector of nonzero elements and vectors of row and column nu | Invert a sparse covariance matrix
For general sparse matrices, very efficient Choleski-based inversion can be done using the SparseM package. The basic steps are to create a vector of nonzero elements and vectors of row and column numbers to which these elements correspond. SparseM takes it from there. I've used this in the R rms package orm function allowing handling of thousands of intercepts in an ordinal regression model. The method for obtaining the equivalent of $(X'X)^{-1}X'Y$ is incredibly fast. A separate inverse is not computed. | Invert a sparse covariance matrix
For general sparse matrices, very efficient Choleski-based inversion can be done using the SparseM package. The basic steps are to create a vector of nonzero elements and vectors of row and column nu |
38,737 | Invert a sparse covariance matrix | Because this is a covariance matrix, $e=h$, $f=l$, $g=m$, and $A,B,C,D$ are all positive. Changing notation to handle a generalization of this problem, consider the symmetric matrix
$$\mathbb{A} = \pmatrix{
\sigma_1^2 & 0 & 0 & \cdots & x_1 \sigma_1 \sigma_n \\
0 & \sigma_2^2 & 0 & \cdots & x_2 \sigma_2 \sigma_n \\
0 & 0 & \sigma_3^2 & \cdots & x_3 \sigma_3 \sigma_n \\
\vdots & \vdots & \vdots & \ddots& \vdots \\
x_1 \sigma_1 \sigma_n & x_2 \sigma_2 \sigma_n & x_3 \sigma_3\sigma_n &\cdots &\sigma_n^2}.$$
By comparing this to the question it is apparent that $n=4$, $\sigma_1 = \sqrt{A}$, $\sigma_2 = \sqrt{B}$, $\sigma_3 = \sqrt{C}$, $\sigma_4=\sigma_n=\sqrt{D}$, and $x_1 = e/(\sigma_1\sigma_n)$ etc. There are $n-1$ such $x_i$.
It is evident that
$$\mathbb{A} = \mathbb{U}\mathbb{X}\mathbb{U}$$
where $\mathbb{U}$ is the diagonal matrix with entries $(\sigma_1, \sigma_2, \ldots, \sigma_n)$ and (therefore)
$$\mathbb{X} = \pmatrix{
1 & 0 & 0 & \cdots & x_1 \\
0 & 1 & 0 & \cdots & x_2 \\
0 & 0 & 1 & \cdots & x_3 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
x_1 & x_2 & x_3 & \cdots & 1}.$$
It is straightforward to demonstrate (inductively) that $\mathbb{X}$ is invertible if and only if $x_1^2 + x_2^2 + \cdots + x_{n-1}^2 \ne 1$. In this case set
$$\Delta = \det(\mathbb{X}) = 1 - (x_1^2 + x_2^2 + \cdots + x_{n-1}^2)$$
and observe (using, for instance, the block-matrix formulae in Glen_b's answer) that
$$\mathbb{X}^{-1} = \frac{1}{\Delta}\pmatrix{
\Delta + x_1^2 & x_1 x_2 & x_1 x_3 & \cdots & -x_1 \\
x_2 x_1 & \Delta + x_2^2 & x_2 x_3 & \cdots & -x_2 \\
x_3 x_1 & x_3 x_2 & \Delta + x_3^2 & \cdots & -x_3 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
-x_1 & -x_2 & -x_3 & \cdots & 1}.$$
The computation of $\mathbb{U}^{-1}$ is simple--invert each of its diagonal entries--and the subsequent construction of
$$\mathbb{A}^{-1} = \mathbb{U}^{-1} \mathbb{X}^{-1} \mathbb{U}^{-1}$$
is equally easy.
To illustrate this algorithm, here is an R implementation. It creates a random symmetric matrix with positive diagonal entries and arbitrary values in the last row and column, inverts it with the algorithm, multiplies that by the original, and compares the result to the identity matrix. The arguments to the inversion function are the vector of $n$ diagonal elements a and the vector of $n-1$ elements in the bottom row of $\mathbb{X}$. Thus $\mathbb{X}$ never actually needs to be constructed.
The timing is a little slower than just using the sparseMatrix class in the Matrix package, because only native R operations (such as outer and t) are employed and these are not optimized for speed. Because the resulting inverse matrix is anything but sparse, there appears to be no inherent advantage to using sparse matrix calculations.
invert <- function(a, y) {
n <- length(a) # The diagonal elements
sigma <- sqrt(a)
x <- (y / (sigma[-n] * sigma[n]))
Delta <- 1 - sum(x*x)
X.inv <- outer(c(x, -1), c(x, -1)) + diag(c(rep(Delta, n-1), 0))
X.inv <- t(t(X.inv) / sigma) / sigma
return (X.inv / Delta)
}
#
# Create a matrix.
#
n <- 4000
a <- rexp(n)
y <- rnorm(n-1)
X <- diag(a)
n <- length(a)
X[-n, n] <- X[n, -n] <- y
#
# Invert it with the algorithm.
#
system.time(X.inv <- invert(a, y))
#
# Check that it is the inverse.
#
if (n <= 1000) {
One <- zapsmall(X %*% X.inv)
if(!all.equal(One, diag(rep(1,n))))
warning("Not an inverse!") else
message("Inverse is correct.")
}
To use the sparse-matrix solver, access the solve function in the Matrix library. Here is an illustration that continues the preceding code.
library(Matrix)
i <- c(1:n, 1:(n-1), rep(n, n-1))
j <- c(1:n, rep(n, n-1), 1:(n-1))
X.0 <- sparseMatrix(i, j, x=c(a, y, y))
system.time(X.0.inv <- solve(X.0)) | Invert a sparse covariance matrix | Because this is a covariance matrix, $e=h$, $f=l$, $g=m$, and $A,B,C,D$ are all positive. Changing notation to handle a generalization of this problem, consider the symmetric matrix
$$\mathbb{A} = \p | Invert a sparse covariance matrix
Because this is a covariance matrix, $e=h$, $f=l$, $g=m$, and $A,B,C,D$ are all positive. Changing notation to handle a generalization of this problem, consider the symmetric matrix
$$\mathbb{A} = \pmatrix{
\sigma_1^2 & 0 & 0 & \cdots & x_1 \sigma_1 \sigma_n \\
0 & \sigma_2^2 & 0 & \cdots & x_2 \sigma_2 \sigma_n \\
0 & 0 & \sigma_3^2 & \cdots & x_3 \sigma_3 \sigma_n \\
\vdots & \vdots & \vdots & \ddots& \vdots \\
x_1 \sigma_1 \sigma_n & x_2 \sigma_2 \sigma_n & x_3 \sigma_3\sigma_n &\cdots &\sigma_n^2}.$$
By comparing this to the question it is apparent that $n=4$, $\sigma_1 = \sqrt{A}$, $\sigma_2 = \sqrt{B}$, $\sigma_3 = \sqrt{C}$, $\sigma_4=\sigma_n=\sqrt{D}$, and $x_1 = e/(\sigma_1\sigma_n)$ etc. There are $n-1$ such $x_i$.
It is evident that
$$\mathbb{A} = \mathbb{U}\mathbb{X}\mathbb{U}$$
where $\mathbb{U}$ is the diagonal matrix with entries $(\sigma_1, \sigma_2, \ldots, \sigma_n)$ and (therefore)
$$\mathbb{X} = \pmatrix{
1 & 0 & 0 & \cdots & x_1 \\
0 & 1 & 0 & \cdots & x_2 \\
0 & 0 & 1 & \cdots & x_3 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
x_1 & x_2 & x_3 & \cdots & 1}.$$
It is straightforward to demonstrate (inductively) that $\mathbb{X}$ is invertible if and only if $x_1^2 + x_2^2 + \cdots + x_{n-1}^2 \ne 1$. In this case set
$$\Delta = \det(\mathbb{X}) = 1 - (x_1^2 + x_2^2 + \cdots + x_{n-1}^2)$$
and observe (using, for instance, the block-matrix formulae in Glen_b's answer) that
$$\mathbb{X}^{-1} = \frac{1}{\Delta}\pmatrix{
\Delta + x_1^2 & x_1 x_2 & x_1 x_3 & \cdots & -x_1 \\
x_2 x_1 & \Delta + x_2^2 & x_2 x_3 & \cdots & -x_2 \\
x_3 x_1 & x_3 x_2 & \Delta + x_3^2 & \cdots & -x_3 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
-x_1 & -x_2 & -x_3 & \cdots & 1}.$$
The computation of $\mathbb{U}^{-1}$ is simple--invert each of its diagonal entries--and the subsequent construction of
$$\mathbb{A}^{-1} = \mathbb{U}^{-1} \mathbb{X}^{-1} \mathbb{U}^{-1}$$
is equally easy.
To illustrate this algorithm, here is an R implementation. It creates a random symmetric matrix with positive diagonal entries and arbitrary values in the last row and column, inverts it with the algorithm, multiplies that by the original, and compares the result to the identity matrix. The arguments to the inversion function are the vector of $n$ diagonal elements a and the vector of $n-1$ elements in the bottom row of $\mathbb{X}$. Thus $\mathbb{X}$ never actually needs to be constructed.
The timing is a little slower than just using the sparseMatrix class in the Matrix package, because only native R operations (such as outer and t) are employed and these are not optimized for speed. Because the resulting inverse matrix is anything but sparse, there appears to be no inherent advantage to using sparse matrix calculations.
invert <- function(a, y) {
n <- length(a) # The diagonal elements
sigma <- sqrt(a)
x <- (y / (sigma[-n] * sigma[n]))
Delta <- 1 - sum(x*x)
X.inv <- outer(c(x, -1), c(x, -1)) + diag(c(rep(Delta, n-1), 0))
X.inv <- t(t(X.inv) / sigma) / sigma
return (X.inv / Delta)
}
#
# Create a matrix.
#
n <- 4000
a <- rexp(n)
y <- rnorm(n-1)
X <- diag(a)
n <- length(a)
X[-n, n] <- X[n, -n] <- y
#
# Invert it with the algorithm.
#
system.time(X.inv <- invert(a, y))
#
# Check that it is the inverse.
#
if (n <= 1000) {
One <- zapsmall(X %*% X.inv)
if(!all.equal(One, diag(rep(1,n))))
warning("Not an inverse!") else
message("Inverse is correct.")
}
To use the sparse-matrix solver, access the solve function in the Matrix library. Here is an illustration that continues the preceding code.
library(Matrix)
i <- c(1:n, 1:(n-1), rep(n, n-1))
j <- c(1:n, rep(n, n-1), 1:(n-1))
X.0 <- sparseMatrix(i, j, x=c(a, y, y))
system.time(X.0.inv <- solve(X.0)) | Invert a sparse covariance matrix
Because this is a covariance matrix, $e=h$, $f=l$, $g=m$, and $A,B,C,D$ are all positive. Changing notation to handle a generalization of this problem, consider the symmetric matrix
$$\mathbb{A} = \p |
38,738 | What is the mathematically rigorous definition of chunky data? | Data like this is often called quantized, particularly when the numbers' precision is limited by the measurement device. For example, a scale might only display integer numbers of grams or pounds. This is particularly common when an analog signal (from a microphone, strain gauge, etc) is digitized. The resulting error (e.g., the difference between 0.012 and 0 for your first data point) is called quantization error. You could also call it rounding or discretization, though this faintly implies that it was done during post-processing.
Truncation also works here, but one needs to distinguish between truncating the range of the observations (e.g., converting anything above 10 into 10, or below 0 to 0) and truncating the values of individual observations.
I'm not aware of a way to robustly detect quantization in any situation. In fact, pretty much all data is quantized to some extent and the amount of quanitization is often known ahead of time from the measuring device's specifications. However, there are some easy heuristics you could try:
How many unique values do you have? Digital-to-analog converters use a fixed number of bits (typically 8, 12, 16, or 24), which gives you $2^8, 2^{12}, 2^{16}$ or $2^{24}$ unique values, and these values are often equally spaced between the maximum and minimum value.
Is there a consistent step-size between the values. In other words, sort them, throw out duplicates, and see if the neighboring values typically increase by the same amount.
Still, I think you'd be better off inquiring about how the data was generated to begin with.
If the data is "mildly" quantized, it's usually not an issue. For example, I wouldn't worry too much if my human subjects' weights were recorded in (integer) pounds or kilograms. If the data is heavily quantized, you could treat it as interval-censored data. This is particularly common in survival analyses, where you might only check to see if someone is alive or something is functioning at some fixed interval (e.g., weekly inspections of a factory). Search for interval regression if this fits your situation.
You should be sure to understand the null hypothesis underlying any tests you run on binned data. For example, data uniformly distributed across 10 bins is quite different from data uniformly distributed across the entire range. | What is the mathematically rigorous definition of chunky data? | Data like this is often called quantized, particularly when the numbers' precision is limited by the measurement device. For example, a scale might only display integer numbers of grams or pounds. Thi | What is the mathematically rigorous definition of chunky data?
Data like this is often called quantized, particularly when the numbers' precision is limited by the measurement device. For example, a scale might only display integer numbers of grams or pounds. This is particularly common when an analog signal (from a microphone, strain gauge, etc) is digitized. The resulting error (e.g., the difference between 0.012 and 0 for your first data point) is called quantization error. You could also call it rounding or discretization, though this faintly implies that it was done during post-processing.
Truncation also works here, but one needs to distinguish between truncating the range of the observations (e.g., converting anything above 10 into 10, or below 0 to 0) and truncating the values of individual observations.
I'm not aware of a way to robustly detect quantization in any situation. In fact, pretty much all data is quantized to some extent and the amount of quanitization is often known ahead of time from the measuring device's specifications. However, there are some easy heuristics you could try:
How many unique values do you have? Digital-to-analog converters use a fixed number of bits (typically 8, 12, 16, or 24), which gives you $2^8, 2^{12}, 2^{16}$ or $2^{24}$ unique values, and these values are often equally spaced between the maximum and minimum value.
Is there a consistent step-size between the values. In other words, sort them, throw out duplicates, and see if the neighboring values typically increase by the same amount.
Still, I think you'd be better off inquiring about how the data was generated to begin with.
If the data is "mildly" quantized, it's usually not an issue. For example, I wouldn't worry too much if my human subjects' weights were recorded in (integer) pounds or kilograms. If the data is heavily quantized, you could treat it as interval-censored data. This is particularly common in survival analyses, where you might only check to see if someone is alive or something is functioning at some fixed interval (e.g., weekly inspections of a factory). Search for interval regression if this fits your situation.
You should be sure to understand the null hypothesis underlying any tests you run on binned data. For example, data uniformly distributed across 10 bins is quite different from data uniformly distributed across the entire range. | What is the mathematically rigorous definition of chunky data?
Data like this is often called quantized, particularly when the numbers' precision is limited by the measurement device. For example, a scale might only display integer numbers of grams or pounds. Thi |
38,739 | What is the mathematically rigorous definition of chunky data? | Generally, "binned data" is how this is referred to.
If you think of a histogram, each bar refers to a bin. If a value is between the upper and lower ends of a given bin, that value is placed in this bin. As an example, if you have binned data due to simple rounding (i.e. a true value of 1.01 becomes represented as 1.0 in the dataset), you can think of observed value 1.0 meaning the true value was actually in the interval [0.5, 1.5).
Typically, this aspect of the data is often ignored; there's often little issue with using the integer age of a subject (28 years) rather than the exact age (28.153...). In the cases the binning effect may be substantial (i.e. years at company; 1/12 is much different than 5/12, but rounded they are both 0), the data can be treated as interval censored to account for this uncertainty in exact response value. | What is the mathematically rigorous definition of chunky data? | Generally, "binned data" is how this is referred to.
If you think of a histogram, each bar refers to a bin. If a value is between the upper and lower ends of a given bin, that value is placed in this | What is the mathematically rigorous definition of chunky data?
Generally, "binned data" is how this is referred to.
If you think of a histogram, each bar refers to a bin. If a value is between the upper and lower ends of a given bin, that value is placed in this bin. As an example, if you have binned data due to simple rounding (i.e. a true value of 1.01 becomes represented as 1.0 in the dataset), you can think of observed value 1.0 meaning the true value was actually in the interval [0.5, 1.5).
Typically, this aspect of the data is often ignored; there's often little issue with using the integer age of a subject (28 years) rather than the exact age (28.153...). In the cases the binning effect may be substantial (i.e. years at company; 1/12 is much different than 5/12, but rounded they are both 0), the data can be treated as interval censored to account for this uncertainty in exact response value. | What is the mathematically rigorous definition of chunky data?
Generally, "binned data" is how this is referred to.
If you think of a histogram, each bar refers to a bin. If a value is between the upper and lower ends of a given bin, that value is placed in this |
38,740 | What is the mathematically rigorous definition of chunky data? | In your case it is called quantization, a common issue with signal processing. Typically you see evenly spaced data (even when you get no multiplicities).
In general (is there are many points close to each other, not necessary with the same value or spacing), look at clustering. For a 1-dimensional values sort them and take a histogram of differences between nearest values. | What is the mathematically rigorous definition of chunky data? | In your case it is called quantization, a common issue with signal processing. Typically you see evenly spaced data (even when you get no multiplicities).
In general (is there are many points close to | What is the mathematically rigorous definition of chunky data?
In your case it is called quantization, a common issue with signal processing. Typically you see evenly spaced data (even when you get no multiplicities).
In general (is there are many points close to each other, not necessary with the same value or spacing), look at clustering. For a 1-dimensional values sort them and take a histogram of differences between nearest values. | What is the mathematically rigorous definition of chunky data?
In your case it is called quantization, a common issue with signal processing. Typically you see evenly spaced data (even when you get no multiplicities).
In general (is there are many points close to |
38,741 | What is the mathematically rigorous definition of chunky data? | To add to the other good answers, and more of a comment on the sources of the chunkiness - quantization can occur for social reasons too, e.g. if you look at a histogram of the diamond dataset in detail you will see pronounced spikes at "nice" values, 0.3, 0.4, 0.5, 0.7, 1.0, 1.2, 1.5, 2.0 etc. There are very few diamonds of weight 0.98, but lots of with a weight just over 1.0, which was explained as - nobody wants to be given a 0.98 carat diamond ... they want a 1.0 carat diamond !!
library(ggplot2)
data(diamonds)
ggplot(diamonds, aes(x=carat)) + geom_histogram(bins=200) + xlim(0,2.1) | What is the mathematically rigorous definition of chunky data? | To add to the other good answers, and more of a comment on the sources of the chunkiness - quantization can occur for social reasons too, e.g. if you look at a histogram of the diamond dataset in deta | What is the mathematically rigorous definition of chunky data?
To add to the other good answers, and more of a comment on the sources of the chunkiness - quantization can occur for social reasons too, e.g. if you look at a histogram of the diamond dataset in detail you will see pronounced spikes at "nice" values, 0.3, 0.4, 0.5, 0.7, 1.0, 1.2, 1.5, 2.0 etc. There are very few diamonds of weight 0.98, but lots of with a weight just over 1.0, which was explained as - nobody wants to be given a 0.98 carat diamond ... they want a 1.0 carat diamond !!
library(ggplot2)
data(diamonds)
ggplot(diamonds, aes(x=carat)) + geom_histogram(bins=200) + xlim(0,2.1) | What is the mathematically rigorous definition of chunky data?
To add to the other good answers, and more of a comment on the sources of the chunkiness - quantization can occur for social reasons too, e.g. if you look at a histogram of the diamond dataset in deta |
38,742 | What is the origin of the term confusion matrix? | The question as I understand is not "where did the grid/matrix come from?" but rather "why is the term 'confusion' used?" I think referring back to Pearson is not likely to help.
My sense, having learned the term in psychology, is that "confusion" refers to the intuition that an item can be correctly or incorrectly labeled/identified/detected and so on (i.e,. "confusion of labels"). Following this logic, I've understood the word "confusion" in this case to loosely refer to the idea: did our classifier (or in the case of psychology, the observer) correctly identify the item, or "was it CONFUSED with another label"? That's my best guess! | What is the origin of the term confusion matrix? | The question as I understand is not "where did the grid/matrix come from?" but rather "why is the term 'confusion' used?" I think referring back to Pearson is not likely to help.
My sense, having lea | What is the origin of the term confusion matrix?
The question as I understand is not "where did the grid/matrix come from?" but rather "why is the term 'confusion' used?" I think referring back to Pearson is not likely to help.
My sense, having learned the term in psychology, is that "confusion" refers to the intuition that an item can be correctly or incorrectly labeled/identified/detected and so on (i.e,. "confusion of labels"). Following this logic, I've understood the word "confusion" in this case to loosely refer to the idea: did our classifier (or in the case of psychology, the observer) correctly identify the item, or "was it CONFUSED with another label"? That's my best guess! | What is the origin of the term confusion matrix?
The question as I understand is not "where did the grid/matrix come from?" but rather "why is the term 'confusion' used?" I think referring back to Pearson is not likely to help.
My sense, having lea |
38,743 | What is the origin of the term confusion matrix? | I think I understand the history of the term, thanks to an answer here: What is the origin of the term confusion matrix?
The confusion matrix was invented at 1904 by Karl Pearson. He used the term Contingency Table. It appeared at Karl Pearson, F.R.S. (1904). Mathematical contributions to the theory of evolution (PDF). Dulau and Co..
During War World 2, Detection Theory was developed as investigation of the relations between stimulus and responds.
The confusion matrix was used there.
Due to detection theory, the term was used in psychology.
From there the term reached machine learning.
It seems that though the concept was invented in statistics, a field very related to machine learning, it reached machine learning after a detour in during a period of 100 years. | What is the origin of the term confusion matrix? | I think I understand the history of the term, thanks to an answer here: What is the origin of the term confusion matrix?
The confusion matrix was invented at 1904 by Karl Pearson. He used the term Con | What is the origin of the term confusion matrix?
I think I understand the history of the term, thanks to an answer here: What is the origin of the term confusion matrix?
The confusion matrix was invented at 1904 by Karl Pearson. He used the term Contingency Table. It appeared at Karl Pearson, F.R.S. (1904). Mathematical contributions to the theory of evolution (PDF). Dulau and Co..
During War World 2, Detection Theory was developed as investigation of the relations between stimulus and responds.
The confusion matrix was used there.
Due to detection theory, the term was used in psychology.
From there the term reached machine learning.
It seems that though the concept was invented in statistics, a field very related to machine learning, it reached machine learning after a detour in during a period of 100 years. | What is the origin of the term confusion matrix?
I think I understand the history of the term, thanks to an answer here: What is the origin of the term confusion matrix?
The confusion matrix was invented at 1904 by Karl Pearson. He used the term Con |
38,744 | What is the origin of the term confusion matrix? | What is odd to many veterans of data science is that what is now often called a confusion matrix has been called a classification matrix in the past. Both have the same structure: predicted outcomes in the columns and actual outcomes in the rows. I've always found the term classification matrix to be less confusing than confusion matrix, and I don't see any advantages to using the newer term. | What is the origin of the term confusion matrix? | What is odd to many veterans of data science is that what is now often called a confusion matrix has been called a classification matrix in the past. Both have the same structure: predicted outcomes | What is the origin of the term confusion matrix?
What is odd to many veterans of data science is that what is now often called a confusion matrix has been called a classification matrix in the past. Both have the same structure: predicted outcomes in the columns and actual outcomes in the rows. I've always found the term classification matrix to be less confusing than confusion matrix, and I don't see any advantages to using the newer term. | What is the origin of the term confusion matrix?
What is odd to many veterans of data science is that what is now often called a confusion matrix has been called a classification matrix in the past. Both have the same structure: predicted outcomes |
38,745 | What is the origin of the term confusion matrix? | It was called a "confusion matrix" by Miller and Nicely in 1955. I don't know if this is the origin of the term "confusion matrix," but it might be.
G.A. Miller and P.E. Nicely, "Analysis of Perceptual Confusions Among Some English Consonants," Journal of the Acoustical Society of America 27:338-352, 1955 | What is the origin of the term confusion matrix? | It was called a "confusion matrix" by Miller and Nicely in 1955. I don't know if this is the origin of the term "confusion matrix," but it might be.
G.A. Miller and P.E. Nicely, "Analysis of Perceptu | What is the origin of the term confusion matrix?
It was called a "confusion matrix" by Miller and Nicely in 1955. I don't know if this is the origin of the term "confusion matrix," but it might be.
G.A. Miller and P.E. Nicely, "Analysis of Perceptual Confusions Among Some English Consonants," Journal of the Acoustical Society of America 27:338-352, 1955 | What is the origin of the term confusion matrix?
It was called a "confusion matrix" by Miller and Nicely in 1955. I don't know if this is the origin of the term "confusion matrix," but it might be.
G.A. Miller and P.E. Nicely, "Analysis of Perceptu |
38,746 | Interpreting test results on log-transformed data | If the logs of the data are really drawn from normally distributed populations with constant variance (but possibly different means), then the original data must have come from lognormal distributions with possibly different scales (due to differences in $\mu$, where adding something to the means on the log-scale has a multiplying effect on the original scale), and hence those populations will also differ in mean.
So a difference in population mean on the log scale will (if the other assumptions of the usual two-sample equal-variance t-test apply) imply a change in mean on the original (untransformed) scale.
You can convert the estimated size of difference on the log scale to a percentage increase on the original scale, and the ends of a confidence interval carry back as well.
So imagine you have an estimated difference in means of about 0.7 ($\hat{\delta}=\hat{\mu}_1-\hat{\mu}_2=0.7$) and (say) a 90% confidence interval for the difference in means of $(0.62, 0.78)$. then the ratio of means of the original populations is estimated to be $\exp(0.7)\approx 2.014$ (i.e. the first group has a mean about twice the size of the second group), and the 90% CI for the ratio of means would be $(e^{0.62}, e^{0.78})\approx (1.86,2.18)$.
Note that p-values carry over directly; we're still performing inference on the parameter $\mu$ (the mean on the log scale). | Interpreting test results on log-transformed data | If the logs of the data are really drawn from normally distributed populations with constant variance (but possibly different means), then the original data must have come from lognormal distributions | Interpreting test results on log-transformed data
If the logs of the data are really drawn from normally distributed populations with constant variance (but possibly different means), then the original data must have come from lognormal distributions with possibly different scales (due to differences in $\mu$, where adding something to the means on the log-scale has a multiplying effect on the original scale), and hence those populations will also differ in mean.
So a difference in population mean on the log scale will (if the other assumptions of the usual two-sample equal-variance t-test apply) imply a change in mean on the original (untransformed) scale.
You can convert the estimated size of difference on the log scale to a percentage increase on the original scale, and the ends of a confidence interval carry back as well.
So imagine you have an estimated difference in means of about 0.7 ($\hat{\delta}=\hat{\mu}_1-\hat{\mu}_2=0.7$) and (say) a 90% confidence interval for the difference in means of $(0.62, 0.78)$. then the ratio of means of the original populations is estimated to be $\exp(0.7)\approx 2.014$ (i.e. the first group has a mean about twice the size of the second group), and the 90% CI for the ratio of means would be $(e^{0.62}, e^{0.78})\approx (1.86,2.18)$.
Note that p-values carry over directly; we're still performing inference on the parameter $\mu$ (the mean on the log scale). | Interpreting test results on log-transformed data
If the logs of the data are really drawn from normally distributed populations with constant variance (but possibly different means), then the original data must have come from lognormal distributions |
38,747 | Interpreting test results on log-transformed data | You're on the right track. You can definitely run a t-test on log-transformed data if it's well-behaved after transformation, and it definitely affects how you interpret your results. In short, you can't make statements about the difference of the means because the mean(log(x)) is not the same as the log(mean(x)) -- the means don't transform well. If you're okay with stating a difference in terms of log-transformed means (i.e. richter scale), then you can definitely do that and just state your results in log(mean) terms. Otherwise, your t-test results will be in tearms of medians, because medians are preserved over a log transformation.
If the data are very normal distributions after a log transform, mean(x) is roughly equal to median(x), and the median(log(x)) is the same as log(median(x)).
Thanks to the log property that allows you to coalesce differences of logs into a log of a ratio
(log(X/Y) = log(X) - log(Y))
you can make statements about the difference in log(medians). You can also can back-transform the CI values back into original units and make a statement about the ratio of the medians with no log() attached. Median is a good measure of center in well-behaved, normally distributed data, so your statistical inference should stand.
Here are the steps:
1. Transform the data (log(x) where x is an array of data in this case)
2. Perform your t-test if your transformed data meet the assumptions of the t-test. Check for:
a. departure from normality
b. significantly differing standard deviations
c. lack of independence.
3. Your CI values will now be in terms of ln(median(X)/median(Y)).
You can back-transform by taking the e-to-the-power-of(confidence interval values)...
This is sometimes written as EXP(<values>).
4. Now you've gotten rid of your ln(Mx/My) problem,
but your confidence interval is still in terms of the RATIO of medians.
5. Your p-value will still stand without transformation.
6. State your conclusions in terms of ratio of medians.
Example: "The median values of x and y are not the same.
We are 95% confident that X's median is between <lowerCI> and <higherCI> times that of Group B."
(because we're still talking median ratio).
This is a bit clunky, so you can also talk in percentages, like "we are 95% confident that X's median is between and that of group Y"
note: I was reading The Statistical Sleuth 3rd Ed and reviewing slides from SMU Data Science Masters course while I wrote this, so credit where credit is due. | Interpreting test results on log-transformed data | You're on the right track. You can definitely run a t-test on log-transformed data if it's well-behaved after transformation, and it definitely affects how you interpret your results. In short, you c | Interpreting test results on log-transformed data
You're on the right track. You can definitely run a t-test on log-transformed data if it's well-behaved after transformation, and it definitely affects how you interpret your results. In short, you can't make statements about the difference of the means because the mean(log(x)) is not the same as the log(mean(x)) -- the means don't transform well. If you're okay with stating a difference in terms of log-transformed means (i.e. richter scale), then you can definitely do that and just state your results in log(mean) terms. Otherwise, your t-test results will be in tearms of medians, because medians are preserved over a log transformation.
If the data are very normal distributions after a log transform, mean(x) is roughly equal to median(x), and the median(log(x)) is the same as log(median(x)).
Thanks to the log property that allows you to coalesce differences of logs into a log of a ratio
(log(X/Y) = log(X) - log(Y))
you can make statements about the difference in log(medians). You can also can back-transform the CI values back into original units and make a statement about the ratio of the medians with no log() attached. Median is a good measure of center in well-behaved, normally distributed data, so your statistical inference should stand.
Here are the steps:
1. Transform the data (log(x) where x is an array of data in this case)
2. Perform your t-test if your transformed data meet the assumptions of the t-test. Check for:
a. departure from normality
b. significantly differing standard deviations
c. lack of independence.
3. Your CI values will now be in terms of ln(median(X)/median(Y)).
You can back-transform by taking the e-to-the-power-of(confidence interval values)...
This is sometimes written as EXP(<values>).
4. Now you've gotten rid of your ln(Mx/My) problem,
but your confidence interval is still in terms of the RATIO of medians.
5. Your p-value will still stand without transformation.
6. State your conclusions in terms of ratio of medians.
Example: "The median values of x and y are not the same.
We are 95% confident that X's median is between <lowerCI> and <higherCI> times that of Group B."
(because we're still talking median ratio).
This is a bit clunky, so you can also talk in percentages, like "we are 95% confident that X's median is between and that of group Y"
note: I was reading The Statistical Sleuth 3rd Ed and reviewing slides from SMU Data Science Masters course while I wrote this, so credit where credit is due. | Interpreting test results on log-transformed data
You're on the right track. You can definitely run a t-test on log-transformed data if it's well-behaved after transformation, and it definitely affects how you interpret your results. In short, you c |
38,748 | Any easy way to cluster GPS trajectories? | There is no easy way.
there is no universally useful accepted definition of what is a cluster, so how could you do clustering?
Similarity is not objective. If you use e.g. DTW then you do assume the complete series is relevant, not e.g. only parts of it. It works on the technology part, but that doesn't mean the results are what you are looking for...
Complexity and cost. In particular if you are interested in partial overlaps, cost rises drastically. Segmentation itself is surprisingly hard and needs to be solved first.
First figure out what you want. Don't start with the method, but with the exact objective: what is a good result (and how would you use it, what is its impact?) | Any easy way to cluster GPS trajectories? | There is no easy way.
there is no universally useful accepted definition of what is a cluster, so how could you do clustering?
Similarity is not objective. If you use e.g. DTW then you do assume the | Any easy way to cluster GPS trajectories?
There is no easy way.
there is no universally useful accepted definition of what is a cluster, so how could you do clustering?
Similarity is not objective. If you use e.g. DTW then you do assume the complete series is relevant, not e.g. only parts of it. It works on the technology part, but that doesn't mean the results are what you are looking for...
Complexity and cost. In particular if you are interested in partial overlaps, cost rises drastically. Segmentation itself is surprisingly hard and needs to be solved first.
First figure out what you want. Don't start with the method, but with the exact objective: what is a good result (and how would you use it, what is its impact?) | Any easy way to cluster GPS trajectories?
There is no easy way.
there is no universally useful accepted definition of what is a cluster, so how could you do clustering?
Similarity is not objective. If you use e.g. DTW then you do assume the |
38,749 | Any easy way to cluster GPS trajectories? | It seems you just need to estimate the spatial distribution of "good" locations belonging to ordinary paths in order to detect outliers, which is a way nicer problem than path clustering.
The naive but likely sufficient way is to convert the entire path bundle into a density raster with a resolution equal to your intended tolerance (~100m), and use it to rise alert whenever the vehicle detours onto an empty pixel (or below some threshold in case your data already has outliers). | Any easy way to cluster GPS trajectories? | It seems you just need to estimate the spatial distribution of "good" locations belonging to ordinary paths in order to detect outliers, which is a way nicer problem than path clustering.
The naive b | Any easy way to cluster GPS trajectories?
It seems you just need to estimate the spatial distribution of "good" locations belonging to ordinary paths in order to detect outliers, which is a way nicer problem than path clustering.
The naive but likely sufficient way is to convert the entire path bundle into a density raster with a resolution equal to your intended tolerance (~100m), and use it to rise alert whenever the vehicle detours onto an empty pixel (or below some threshold in case your data already has outliers). | Any easy way to cluster GPS trajectories?
It seems you just need to estimate the spatial distribution of "good" locations belonging to ordinary paths in order to detect outliers, which is a way nicer problem than path clustering.
The naive b |
38,750 | Any easy way to cluster GPS trajectories? | Consider phrasing the problem as a graph of locations that make up a path and you want to find commonly occurring subgraphs. Try looking at frequent pattern mining approaches, specifically mining graphs, trees and structures.
I originally ran across this idea in the gSpan algorithm. It finds a hierarchy of subgraphs (from small to large) and does it efficiently by creating a lexigraphical order of nodes to traverse. The authors even have an implementation of gSpan to use.
You may run into problems with graph based approaches since I assume it's very unlikely that two lat/longs are exactly the same and you may need to round things off. | Any easy way to cluster GPS trajectories? | Consider phrasing the problem as a graph of locations that make up a path and you want to find commonly occurring subgraphs. Try looking at frequent pattern mining approaches, specifically mining grap | Any easy way to cluster GPS trajectories?
Consider phrasing the problem as a graph of locations that make up a path and you want to find commonly occurring subgraphs. Try looking at frequent pattern mining approaches, specifically mining graphs, trees and structures.
I originally ran across this idea in the gSpan algorithm. It finds a hierarchy of subgraphs (from small to large) and does it efficiently by creating a lexigraphical order of nodes to traverse. The authors even have an implementation of gSpan to use.
You may run into problems with graph based approaches since I assume it's very unlikely that two lat/longs are exactly the same and you may need to round things off. | Any easy way to cluster GPS trajectories?
Consider phrasing the problem as a graph of locations that make up a path and you want to find commonly occurring subgraphs. Try looking at frequent pattern mining approaches, specifically mining grap |
38,751 | Any easy way to cluster GPS trajectories? | There are many different forms to approach this problem. There are a lot of research works done in this field (I guess since 2000) and a hand full of algorithms are introduced. Recently I read a good comprehensive survey that I recommend you read it: "Trajectory data mining: an overview" by YU ZHENG, Microsoft Research. To find your answer easier, you can directly read "Sequential pattern mining", "Distance/Similarity of Trajectories" and "Trajectory Clustering" sections which are more informative considering your question. | Any easy way to cluster GPS trajectories? | There are many different forms to approach this problem. There are a lot of research works done in this field (I guess since 2000) and a hand full of algorithms are introduced. Recently I read a good | Any easy way to cluster GPS trajectories?
There are many different forms to approach this problem. There are a lot of research works done in this field (I guess since 2000) and a hand full of algorithms are introduced. Recently I read a good comprehensive survey that I recommend you read it: "Trajectory data mining: an overview" by YU ZHENG, Microsoft Research. To find your answer easier, you can directly read "Sequential pattern mining", "Distance/Similarity of Trajectories" and "Trajectory Clustering" sections which are more informative considering your question. | Any easy way to cluster GPS trajectories?
There are many different forms to approach this problem. There are a lot of research works done in this field (I guess since 2000) and a hand full of algorithms are introduced. Recently I read a good |
38,752 | Test if two coefficients are statistically different in logistic regression? | There's a couple of these questions floating around that essentially have the same answer. There are essentially two approaches to testing what are model constraints.
Given a regression $Y = \beta_0 + \beta_1X_1 + \beta_2X_2 $, you can
1. Modify ("constrain") the regression structure and perform some kind of test
Write out what you want to test and substitute into the regression formula , e.g.
$\beta_1 = \beta_2$
which substitutes in as
$Y = \beta_0 + \beta_1 X_3 $ where $X_3 = X_1 + X_2$
You now have two models, the original and restricted, and you perform a likelihood ratio test between the two. This is the method discussed by @Sid and @Analyst using lratiotest
Alternatively in the same spirit:
$\beta_1 = \beta_2$ equivalent to
$\beta_1 - \beta_2 = 0$ which can be rewritten as
$\beta_1 - \beta_2 = \alpha$
Substitute this back into the original regression formulation
$ Y = \beta_0 + (\alpha + \beta_2) X_1 + \beta_2X_2 $
$ Y = \beta_0 + \alpha X_1 + \beta_2 X_3 $ after rearranging
Here, a test of $\alpha$ is a test of $\beta_1 = \beta_2$ in the original regression. This is the method shown by @Glen_b here.
This method is usable with other hypothesis as well, like $\beta_1 = 0.5$ or $\beta_1 = 3\beta_2$; just substitute as appropriate.
2. Perform what are known as "general linear hypothesis" or "regression Wald tests" after estimation. They have more names, another common one is "linear contrasts", and I've seen others as well.
Once you have your vector of regression coefficients
$\mathbf{B} = [\text{b x 1}] = [\beta_0, \beta_1, \beta_2]'$
and their var-covariance matrix
$\mathbf{V} = [\text{b x b}] = [\text{stuff}]$
You construct a vector defining your hypothesis. So in this case, where we want to test $\beta_1 - \beta_2 = 0$, we have
$H = [\text{1 x b}] = [0,1,-1]$
resulting in a hypothesis of
$HB = [0,1,-1] \times [\beta_0, \beta_1, \beta_2]'$
If you wanted to test against something other than 0, then you would subtract the constant as such
$HB - c$
Then you calculate the test statistic
$S = (HB - c)'(HVH')^{-1}(HB -c)$
This is distributed $~\chi^2_1$ for logistic regression (in linear regression, it is an F-statistic).
In MATLAB, it looks like linhyptest is what you want for this.
As with #1, this is usable with any other hypothesis that involve linear combinations of the coefficients. $\beta_1 = 0.5$ or $\beta_1 = 3\beta_2$ fit easily into this framework; construct $H$ and $c$ as appropriate.
I have a preference for the second method. It has the advantage of not requiring refitting a second model, reducing the work in sorting out how the second model should be formulated, especially if you have multiple hypothesis. In addition, multiple hypothesis can be tested jointly as well by "stacking" the $H$ and $c$ vectors, turning $H$ into a $\text{q x b}$ and $c$ into a $\text{q x 1}$, with the resulting test statistic having $q$ degrees of freedom instead of 1. | Test if two coefficients are statistically different in logistic regression? | There's a couple of these questions floating around that essentially have the same answer. There are essentially two approaches to testing what are model constraints.
Given a regression $Y = \beta_0 + | Test if two coefficients are statistically different in logistic regression?
There's a couple of these questions floating around that essentially have the same answer. There are essentially two approaches to testing what are model constraints.
Given a regression $Y = \beta_0 + \beta_1X_1 + \beta_2X_2 $, you can
1. Modify ("constrain") the regression structure and perform some kind of test
Write out what you want to test and substitute into the regression formula , e.g.
$\beta_1 = \beta_2$
which substitutes in as
$Y = \beta_0 + \beta_1 X_3 $ where $X_3 = X_1 + X_2$
You now have two models, the original and restricted, and you perform a likelihood ratio test between the two. This is the method discussed by @Sid and @Analyst using lratiotest
Alternatively in the same spirit:
$\beta_1 = \beta_2$ equivalent to
$\beta_1 - \beta_2 = 0$ which can be rewritten as
$\beta_1 - \beta_2 = \alpha$
Substitute this back into the original regression formulation
$ Y = \beta_0 + (\alpha + \beta_2) X_1 + \beta_2X_2 $
$ Y = \beta_0 + \alpha X_1 + \beta_2 X_3 $ after rearranging
Here, a test of $\alpha$ is a test of $\beta_1 = \beta_2$ in the original regression. This is the method shown by @Glen_b here.
This method is usable with other hypothesis as well, like $\beta_1 = 0.5$ or $\beta_1 = 3\beta_2$; just substitute as appropriate.
2. Perform what are known as "general linear hypothesis" or "regression Wald tests" after estimation. They have more names, another common one is "linear contrasts", and I've seen others as well.
Once you have your vector of regression coefficients
$\mathbf{B} = [\text{b x 1}] = [\beta_0, \beta_1, \beta_2]'$
and their var-covariance matrix
$\mathbf{V} = [\text{b x b}] = [\text{stuff}]$
You construct a vector defining your hypothesis. So in this case, where we want to test $\beta_1 - \beta_2 = 0$, we have
$H = [\text{1 x b}] = [0,1,-1]$
resulting in a hypothesis of
$HB = [0,1,-1] \times [\beta_0, \beta_1, \beta_2]'$
If you wanted to test against something other than 0, then you would subtract the constant as such
$HB - c$
Then you calculate the test statistic
$S = (HB - c)'(HVH')^{-1}(HB -c)$
This is distributed $~\chi^2_1$ for logistic regression (in linear regression, it is an F-statistic).
In MATLAB, it looks like linhyptest is what you want for this.
As with #1, this is usable with any other hypothesis that involve linear combinations of the coefficients. $\beta_1 = 0.5$ or $\beta_1 = 3\beta_2$ fit easily into this framework; construct $H$ and $c$ as appropriate.
I have a preference for the second method. It has the advantage of not requiring refitting a second model, reducing the work in sorting out how the second model should be formulated, especially if you have multiple hypothesis. In addition, multiple hypothesis can be tested jointly as well by "stacking" the $H$ and $c$ vectors, turning $H$ into a $\text{q x b}$ and $c$ into a $\text{q x 1}$, with the resulting test statistic having $q$ degrees of freedom instead of 1. | Test if two coefficients are statistically different in logistic regression?
There's a couple of these questions floating around that essentially have the same answer. There are essentially two approaches to testing what are model constraints.
Given a regression $Y = \beta_0 + |
38,753 | Test if two coefficients are statistically different in logistic regression? | You can specify two models: 1) Model with parameter restrictions 2) Model without these.
Next you can test via likelihood ratio test if your restricted model should be abandoned in favor of unrestricted one. So null hypothesis is restricted model, which is not accepted but can only be rejected.
Here is link to implementation in MATLAB:
http://se.mathworks.com/help/econ/lratiotest.html
Unfortunately I cannot help you further since I do not have MATLAB software myself. | Test if two coefficients are statistically different in logistic regression? | You can specify two models: 1) Model with parameter restrictions 2) Model without these.
Next you can test via likelihood ratio test if your restricted model should be abandoned in favor of unrestri | Test if two coefficients are statistically different in logistic regression?
You can specify two models: 1) Model with parameter restrictions 2) Model without these.
Next you can test via likelihood ratio test if your restricted model should be abandoned in favor of unrestricted one. So null hypothesis is restricted model, which is not accepted but can only be rejected.
Here is link to implementation in MATLAB:
http://se.mathworks.com/help/econ/lratiotest.html
Unfortunately I cannot help you further since I do not have MATLAB software myself. | Test if two coefficients are statistically different in logistic regression?
You can specify two models: 1) Model with parameter restrictions 2) Model without these.
Next you can test via likelihood ratio test if your restricted model should be abandoned in favor of unrestri |
38,754 | Test if two coefficients are statistically different in logistic regression? | Questions of this form in hypothesis testing are generally answered by testing the hypothesis that the difference of two parameters is greater than zero. I am not aware of a direct approach, but this is one possibility. Suppose you want to test if $a$ is statistically different from $b$ in
$logit (z) = aX + bY$ ..(1)
fit
$logit(z) = aX + aY$ ..(2)
and compare the fits in (1) and (2) using methods described by @Analyst. If the fits are drastically different, I would conclude the parameters are statistically different | Test if two coefficients are statistically different in logistic regression? | Questions of this form in hypothesis testing are generally answered by testing the hypothesis that the difference of two parameters is greater than zero. I am not aware of a direct approach, but this | Test if two coefficients are statistically different in logistic regression?
Questions of this form in hypothesis testing are generally answered by testing the hypothesis that the difference of two parameters is greater than zero. I am not aware of a direct approach, but this is one possibility. Suppose you want to test if $a$ is statistically different from $b$ in
$logit (z) = aX + bY$ ..(1)
fit
$logit(z) = aX + aY$ ..(2)
and compare the fits in (1) and (2) using methods described by @Analyst. If the fits are drastically different, I would conclude the parameters are statistically different | Test if two coefficients are statistically different in logistic regression?
Questions of this form in hypothesis testing are generally answered by testing the hypothesis that the difference of two parameters is greater than zero. I am not aware of a direct approach, but this |
38,755 | Test if two coefficients are statistically different in logistic regression? | LR test may be similar to F-test in linear regression. If individual coefficients are to be compared, something like t-test may be more relevant.
GLM, if estimated by maximum likelihood estimation, coefficient estimators follow the normal distribution asymtotically and this is why Z-test is normally performed rather than t-test for individual coefficients. Then it'd be quite similar to testing of mean difference. | Test if two coefficients are statistically different in logistic regression? | LR test may be similar to F-test in linear regression. If individual coefficients are to be compared, something like t-test may be more relevant.
GLM, if estimated by maximum likelihood estimation, co | Test if two coefficients are statistically different in logistic regression?
LR test may be similar to F-test in linear regression. If individual coefficients are to be compared, something like t-test may be more relevant.
GLM, if estimated by maximum likelihood estimation, coefficient estimators follow the normal distribution asymtotically and this is why Z-test is normally performed rather than t-test for individual coefficients. Then it'd be quite similar to testing of mean difference. | Test if two coefficients are statistically different in logistic regression?
LR test may be similar to F-test in linear regression. If individual coefficients are to be compared, something like t-test may be more relevant.
GLM, if estimated by maximum likelihood estimation, co |
38,756 | Textbooks on linear regression with least squares | I suggest John Fox's "Applied Regression Analysis and Generalized Linear Models" and its companion text "An R Companion to Applied Regression" for one text on regression. James and Hastie's text is introducing regression to develop ideas for statistical learning. Faraway's text has many insights, but is terse. Gelman's book is also nice, but not my suggestion for an introduction to regression. I suggest Fox's text because it is relatively clear, introductory but covers many topics in depth, and has an R companion. | Textbooks on linear regression with least squares | I suggest John Fox's "Applied Regression Analysis and Generalized Linear Models" and its companion text "An R Companion to Applied Regression" for one text on regression. James and Hastie's text is in | Textbooks on linear regression with least squares
I suggest John Fox's "Applied Regression Analysis and Generalized Linear Models" and its companion text "An R Companion to Applied Regression" for one text on regression. James and Hastie's text is introducing regression to develop ideas for statistical learning. Faraway's text has many insights, but is terse. Gelman's book is also nice, but not my suggestion for an introduction to regression. I suggest Fox's text because it is relatively clear, introductory but covers many topics in depth, and has an R companion. | Textbooks on linear regression with least squares
I suggest John Fox's "Applied Regression Analysis and Generalized Linear Models" and its companion text "An R Companion to Applied Regression" for one text on regression. James and Hastie's text is in |
38,757 | Textbooks on linear regression with least squares | Practical Regression and Anova using R by Julian Faraway is a good book, and is freely available.
If you happen to read French, I recommend Régression, Théorie et applications by Cornillon and Matzner-Løber. | Textbooks on linear regression with least squares | Practical Regression and Anova using R by Julian Faraway is a good book, and is freely available.
If you happen to read French, I recommend Régression, Théorie et applications by Cornillon and Matzne | Textbooks on linear regression with least squares
Practical Regression and Anova using R by Julian Faraway is a good book, and is freely available.
If you happen to read French, I recommend Régression, Théorie et applications by Cornillon and Matzner-Løber. | Textbooks on linear regression with least squares
Practical Regression and Anova using R by Julian Faraway is a good book, and is freely available.
If you happen to read French, I recommend Régression, Théorie et applications by Cornillon and Matzne |
38,758 | Textbooks on linear regression with least squares | I like "Data Analysis Using Regression and Multilevel/Hierarchical Models" by Andrew Gelman and Jennifer Hill.
"Extending the Linear Model with R" by Julian Faraway has a great introductory chapter which goes into the general linear model (regression). I've never used "Practical Regression and Anova using R", however a a quick glance it looks good as well! | Textbooks on linear regression with least squares | I like "Data Analysis Using Regression and Multilevel/Hierarchical Models" by Andrew Gelman and Jennifer Hill.
"Extending the Linear Model with R" by Julian Faraway has a great introductory chapter wh | Textbooks on linear regression with least squares
I like "Data Analysis Using Regression and Multilevel/Hierarchical Models" by Andrew Gelman and Jennifer Hill.
"Extending the Linear Model with R" by Julian Faraway has a great introductory chapter which goes into the general linear model (regression). I've never used "Practical Regression and Anova using R", however a a quick glance it looks good as well! | Textbooks on linear regression with least squares
I like "Data Analysis Using Regression and Multilevel/Hierarchical Models" by Andrew Gelman and Jennifer Hill.
"Extending the Linear Model with R" by Julian Faraway has a great introductory chapter wh |
38,759 | Textbooks on linear regression with least squares | I have two recommendations.
Since you say you have no background in Statistics I think a good beginning would be: "OpenIntro Statistics" by Diez, Barr, and Çetinkaya-Rundel. It goes from the basic concepts and has an introduction to regression. You can download it here. There is a Data Analysis and Statistical Inference course in Coursera that is based on this book.
After getting the basic concepts, I would then suggest going to "Introduction to Statistical Learning" by James, Witten, Hastie, and Tibshirani. There, regression is treated with more depth. You can also download the source codes in R as well as all the datasets they use. All the material can be downloaded here. There is a Statistical Learning MOOC that covers this book. | Textbooks on linear regression with least squares | I have two recommendations.
Since you say you have no background in Statistics I think a good beginning would be: "OpenIntro Statistics" by Diez, Barr, and Çetinkaya-Rundel. It goes from the basic con | Textbooks on linear regression with least squares
I have two recommendations.
Since you say you have no background in Statistics I think a good beginning would be: "OpenIntro Statistics" by Diez, Barr, and Çetinkaya-Rundel. It goes from the basic concepts and has an introduction to regression. You can download it here. There is a Data Analysis and Statistical Inference course in Coursera that is based on this book.
After getting the basic concepts, I would then suggest going to "Introduction to Statistical Learning" by James, Witten, Hastie, and Tibshirani. There, regression is treated with more depth. You can also download the source codes in R as well as all the datasets they use. All the material can be downloaded here. There is a Statistical Learning MOOC that covers this book. | Textbooks on linear regression with least squares
I have two recommendations.
Since you say you have no background in Statistics I think a good beginning would be: "OpenIntro Statistics" by Diez, Barr, and Çetinkaya-Rundel. It goes from the basic con |
38,760 | Textbooks on linear regression with least squares | I would like to add a book which I randomly found in my university library. It's called Correlation and Regression by Philip Bobko. It is very easy to read and draws bridges between different concepts very elegantly, like f.e. the regression slope and the correlation coefficient. | Textbooks on linear regression with least squares | I would like to add a book which I randomly found in my university library. It's called Correlation and Regression by Philip Bobko. It is very easy to read and draws bridges between different concepts | Textbooks on linear regression with least squares
I would like to add a book which I randomly found in my university library. It's called Correlation and Regression by Philip Bobko. It is very easy to read and draws bridges between different concepts very elegantly, like f.e. the regression slope and the correlation coefficient. | Textbooks on linear regression with least squares
I would like to add a book which I randomly found in my university library. It's called Correlation and Regression by Philip Bobko. It is very easy to read and draws bridges between different concepts |
38,761 | Asymptotic distribution of the max (min) of IID binomial variables | The limit with $k/n\rightarrow\lambda$ isn't very interesting. But if you let the sample size increase exponentially with $n$ then you get a limiting distribution, which is a "discrete Gumbel" (pace the comments above). For example, for simplicity, let $p=0.5$, so $X_i$ are IID $B(n,0.5)$, where $n$ is large, and the sample size $k$ increases exponentially (but remains much less than $2^n$) - say $k=2^m$ where $n>m>\frac{n}{2}$. Suppose we are interested in the minimum rather than the maximum (it comes to the same thing but it's a bit easier to write down). The Normal approximation is completely useless with a very large sample - it will usually suggest a negative minimum.
The distribution of the minimum will be clustered around a value $d$ where $\mathbb{P}(X_i\le d)\approx 2^{-m}$, so that $\mathbb{P}(min(X_i)>d)\approx e^{-1}$. The working below shows that $d$ will not approach zero until $m$ is close to $n$ - in fact $\frac{d}{n}$ will be nearly constant for a given ratio $\frac{m}{n}$. And in that region the Binomial distribution will be close to a discrete (reversed) exponential, so the distribution of the minimum will be close to a discretised reversed Gumbel distribution.
Working out the details: using the Stirling approximation for factorial, we can approximate the binomial coefficient as:
$$\binom{n}{d}\approx \frac{1}{\sqrt{2\pi n}}\left(\frac{d}{n}\right)^{-d-1/2}\left(1-\frac{d}{n}\right)^{-n+d-1/2}.$$
If $n\gg d\gg 1$, then for $j\ge0$,
$$\mathbb{P}(X_i=d-j)\approx \left(\frac{d}{n-d}\right)^j\mathbb{P}(X_i=d)$$
(the successive ratios between binomial coefficients change slowly while the product goes quickly to zero), so
$$\mathbb{P}(X_i\le d) \approx \left(1-\frac{d}{n}\right)\left(1-2\frac{d}{n}\right)^{-1}\mathbb{P}(X_i=d).$$
Combining the above to get an expression for the cumulative probability, setting that cumulative probability equal to $2^{-m}$, multiplying through by $2^n$, taking logs and dividing by $n$, we end up with: $$-\left(\frac{d}{n}+\frac{1}{2n}\right)log\left(\frac{d}{n}\right)-\left(1-\frac{d}{n}-\frac{1}{2n}\right)log\left(1-\frac{d}{n}\right)-\frac{1}{n}log\left(1-2\frac{d}{n}\right)=log(2)\left(1-\frac{m}{n}\right)+log(2\pi n)/2n.$$
Writing $\nu=\frac{d}{n}+\frac{1}{2n}$, and noting that $\alpha.log(\alpha+\delta)\approx \alpha.log(\alpha)+\delta$ for small $\delta$:
$$-\nu.log(\nu)-(1-\nu)log(1-\nu)-\frac{1}{n}log(1-2\nu)=log(2)\left(1-\frac{m}{n}\right)+log(2\pi n)/2n.$$
This can be solved with Newton-Raphson easily enough. Discounting the small third term (the value of $d$ is affected by at most 0.15 for $n\ge 100, m\ge n/2$) we see that $\frac{d}{n}$ is effectively only dependent on $\frac{m}{n}$ if $n$ is large, and it does not tend to zero as $n$ and $m$ increase in constant ratio.
Having found a continuous solution $d$ we round to the nearest integer $\hat{d}$. (Could be a bit more careful about continuity correction and rounding the right way but it isn't necessary here.) Write $\hat{\lambda}=\frac{n-\hat{d}}{\hat{d}}>1$. Write $\rho=2^m\mathbb{P}(X_i\le\hat{d})$: we expect $1/\sqrt{\hat{\lambda}}\le\rho\le\sqrt{\hat{\lambda}}$. Then:
$$\mathbb{P}(X_i=\hat{d}-j)\approx\mathbb{P}(X_i=\hat{d})\hat{\lambda}^{-j},$$
and this approximation gets better as $n$ and $\hat{d}$ increase together. So:
$$\mathbb{P}(X_i\le\hat{d}-j)\approx\mathbb{P}(X_i\le\hat{d})\hat{\lambda}^{-j}=2^{-m}\rho\hat{\lambda}^{-j},$$ and so
$$\mathbb{P}(min(X_i)>\hat{d}-j)=(1-\mathbb{P}(X_i\le\hat{d}-j))^{2^m}\approx (1-2^{-m}\rho\hat{\lambda}^{-j})^{2^m}=e^{-\rho\hat{\lambda}^{-j}}.$$
If we write $x=\hat{d}-j$ then
$$\rho\hat{\lambda}^{-j}=e^{log(\rho)-\hat{d}.log(\hat{\lambda})+x.log(\hat{\lambda})},$$so
$$\mathbb{P}(min(X_i)>x)\approx exp(-e^{\frac{x-\mu}{\sigma}}),$$
which is a discrete reversed Gumbel with parameters $\mu=\hat{d}-\frac{log(\rho)}{log(\hat{\lambda})}$ and $\sigma=\frac{1}{log(\hat{\lambda})}$.
$$\hat{\lambda}\approx\lambda=\frac{n-d}{d}\text{, and }\hat{d}-\frac{log(\rho)}{log(\hat{\lambda})}\approx d.$$
Exercise for the reader - $p\ne0.5$? | Asymptotic distribution of the max (min) of IID binomial variables | The limit with $k/n\rightarrow\lambda$ isn't very interesting. But if you let the sample size increase exponentially with $n$ then you get a limiting distribution, which is a "discrete Gumbel" (pace | Asymptotic distribution of the max (min) of IID binomial variables
The limit with $k/n\rightarrow\lambda$ isn't very interesting. But if you let the sample size increase exponentially with $n$ then you get a limiting distribution, which is a "discrete Gumbel" (pace the comments above). For example, for simplicity, let $p=0.5$, so $X_i$ are IID $B(n,0.5)$, where $n$ is large, and the sample size $k$ increases exponentially (but remains much less than $2^n$) - say $k=2^m$ where $n>m>\frac{n}{2}$. Suppose we are interested in the minimum rather than the maximum (it comes to the same thing but it's a bit easier to write down). The Normal approximation is completely useless with a very large sample - it will usually suggest a negative minimum.
The distribution of the minimum will be clustered around a value $d$ where $\mathbb{P}(X_i\le d)\approx 2^{-m}$, so that $\mathbb{P}(min(X_i)>d)\approx e^{-1}$. The working below shows that $d$ will not approach zero until $m$ is close to $n$ - in fact $\frac{d}{n}$ will be nearly constant for a given ratio $\frac{m}{n}$. And in that region the Binomial distribution will be close to a discrete (reversed) exponential, so the distribution of the minimum will be close to a discretised reversed Gumbel distribution.
Working out the details: using the Stirling approximation for factorial, we can approximate the binomial coefficient as:
$$\binom{n}{d}\approx \frac{1}{\sqrt{2\pi n}}\left(\frac{d}{n}\right)^{-d-1/2}\left(1-\frac{d}{n}\right)^{-n+d-1/2}.$$
If $n\gg d\gg 1$, then for $j\ge0$,
$$\mathbb{P}(X_i=d-j)\approx \left(\frac{d}{n-d}\right)^j\mathbb{P}(X_i=d)$$
(the successive ratios between binomial coefficients change slowly while the product goes quickly to zero), so
$$\mathbb{P}(X_i\le d) \approx \left(1-\frac{d}{n}\right)\left(1-2\frac{d}{n}\right)^{-1}\mathbb{P}(X_i=d).$$
Combining the above to get an expression for the cumulative probability, setting that cumulative probability equal to $2^{-m}$, multiplying through by $2^n$, taking logs and dividing by $n$, we end up with: $$-\left(\frac{d}{n}+\frac{1}{2n}\right)log\left(\frac{d}{n}\right)-\left(1-\frac{d}{n}-\frac{1}{2n}\right)log\left(1-\frac{d}{n}\right)-\frac{1}{n}log\left(1-2\frac{d}{n}\right)=log(2)\left(1-\frac{m}{n}\right)+log(2\pi n)/2n.$$
Writing $\nu=\frac{d}{n}+\frac{1}{2n}$, and noting that $\alpha.log(\alpha+\delta)\approx \alpha.log(\alpha)+\delta$ for small $\delta$:
$$-\nu.log(\nu)-(1-\nu)log(1-\nu)-\frac{1}{n}log(1-2\nu)=log(2)\left(1-\frac{m}{n}\right)+log(2\pi n)/2n.$$
This can be solved with Newton-Raphson easily enough. Discounting the small third term (the value of $d$ is affected by at most 0.15 for $n\ge 100, m\ge n/2$) we see that $\frac{d}{n}$ is effectively only dependent on $\frac{m}{n}$ if $n$ is large, and it does not tend to zero as $n$ and $m$ increase in constant ratio.
Having found a continuous solution $d$ we round to the nearest integer $\hat{d}$. (Could be a bit more careful about continuity correction and rounding the right way but it isn't necessary here.) Write $\hat{\lambda}=\frac{n-\hat{d}}{\hat{d}}>1$. Write $\rho=2^m\mathbb{P}(X_i\le\hat{d})$: we expect $1/\sqrt{\hat{\lambda}}\le\rho\le\sqrt{\hat{\lambda}}$. Then:
$$\mathbb{P}(X_i=\hat{d}-j)\approx\mathbb{P}(X_i=\hat{d})\hat{\lambda}^{-j},$$
and this approximation gets better as $n$ and $\hat{d}$ increase together. So:
$$\mathbb{P}(X_i\le\hat{d}-j)\approx\mathbb{P}(X_i\le\hat{d})\hat{\lambda}^{-j}=2^{-m}\rho\hat{\lambda}^{-j},$$ and so
$$\mathbb{P}(min(X_i)>\hat{d}-j)=(1-\mathbb{P}(X_i\le\hat{d}-j))^{2^m}\approx (1-2^{-m}\rho\hat{\lambda}^{-j})^{2^m}=e^{-\rho\hat{\lambda}^{-j}}.$$
If we write $x=\hat{d}-j$ then
$$\rho\hat{\lambda}^{-j}=e^{log(\rho)-\hat{d}.log(\hat{\lambda})+x.log(\hat{\lambda})},$$so
$$\mathbb{P}(min(X_i)>x)\approx exp(-e^{\frac{x-\mu}{\sigma}}),$$
which is a discrete reversed Gumbel with parameters $\mu=\hat{d}-\frac{log(\rho)}{log(\hat{\lambda})}$ and $\sigma=\frac{1}{log(\hat{\lambda})}$.
$$\hat{\lambda}\approx\lambda=\frac{n-d}{d}\text{, and }\hat{d}-\frac{log(\rho)}{log(\hat{\lambda})}\approx d.$$
Exercise for the reader - $p\ne0.5$? | Asymptotic distribution of the max (min) of IID binomial variables
The limit with $k/n\rightarrow\lambda$ isn't very interesting. But if you let the sample size increase exponentially with $n$ then you get a limiting distribution, which is a "discrete Gumbel" (pace |
38,762 | Asymptotic distribution of the max (min) of IID binomial variables | Since the answer of @Boddle does not give the detail for the case $p \neq 1/2$, I will provide it here.
First off, the geometric approximation still holds for $n \gg d \gg 1$. For $j \geq 0$ we obtain
$$ \mathbb{P}(X_i = d-j) \approx \left(\frac{1-p}{p}\frac{d}{n-d}\right)^j \mathbb{P}(X_i = d).$$
Next, we need to compute $d$ such that $\mathbb{P}(X_i \leq d) \approx 2^{-m}$, which was done by a numerical solving approach, so it will not cause any major difficulty. By summing over all values of $j$, we obtain
$$\mathbb{P}(X_i \leq d) \approx \left(1-\frac{d}{n}\right)\left(1-\frac{1}{p}\frac{d}{n}\right)^{-1}.$$
Following the same procedure as @Boddle suggests, but without multiplying through by $2^n$, we obtain the following equation
$$-\left(\frac{d}{n}+\frac{1}{2n}\right)\log\left(\frac{d}{n}\right)
-\left(1-\frac{d}{n}-\frac{1}{2n}\right)\log\left(1-\frac{d}{n}\right)
-\frac{1}{n}\log\left(1-\frac{1}{p}\frac{d}{n}\right)
+\left(\frac{d}{n}+\frac{1}{2n}\right)\log\left(\frac{p}{1-p}\right) =
-\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n)\right).$$
Again defining $\nu = \frac{d}{n} + \frac{1}{2n}$, we obtain an equation of which the solution can be found numerically
$$-\nu\log(\nu) - (1-\nu)\log(1-\nu) -\frac{1}{n}\log(1-\nu/p) + \nu\log\left(\frac{p}{1-p}\right) \\
= -\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n)\right).$$
Again, it is clear that the value of $\nu$ depends only on the ratio $\frac{m}{n}$ for large $n$. From the solution of the equation above, we can get to the value of $d$ and $\hat{d}$ and finally we define $\hat{\lambda} = \frac{p}{1-p}\frac{n-\hat{d}}{\hat{d}}$. From here on, the solution is as explained by @Boddle with this change of definition.
It is also useful to give the solution in the case $k \sim \gamma 2^m$, where $\gamma > 0$. We need to find $d$ such that $\mathbb{P}(X_i \leq d) \approx \frac{2^{-m}}{\gamma}$ to maintain $\mathbb{P}(\min X_i > d) \approx e^{-1}$. We can see that nothing changes, except that the equation to solve numerically now becomes
$$-\nu\log(\nu) - (1-\nu)\log(1-\nu) -\frac{1}{n}\log(1-\nu/p) + \nu\log\left(\frac{p}{1-p}\right) \\
= -\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n) + 2\log(\gamma)\right).$$
For large $n$, the difference becomes negligible and the solution is approximately the same as above.
I computed the values of $d/n$ as a function of $m/n$ for infinitely large $n$ using the equations above. I show the curves on the plot below for different values of $p \geq 1/2$. This gives an idea of the expected value of the minimum as $k=2^m$ increases relative to m. | Asymptotic distribution of the max (min) of IID binomial variables | Since the answer of @Boddle does not give the detail for the case $p \neq 1/2$, I will provide it here.
First off, the geometric approximation still holds for $n \gg d \gg 1$. For $j \geq 0$ we obtain | Asymptotic distribution of the max (min) of IID binomial variables
Since the answer of @Boddle does not give the detail for the case $p \neq 1/2$, I will provide it here.
First off, the geometric approximation still holds for $n \gg d \gg 1$. For $j \geq 0$ we obtain
$$ \mathbb{P}(X_i = d-j) \approx \left(\frac{1-p}{p}\frac{d}{n-d}\right)^j \mathbb{P}(X_i = d).$$
Next, we need to compute $d$ such that $\mathbb{P}(X_i \leq d) \approx 2^{-m}$, which was done by a numerical solving approach, so it will not cause any major difficulty. By summing over all values of $j$, we obtain
$$\mathbb{P}(X_i \leq d) \approx \left(1-\frac{d}{n}\right)\left(1-\frac{1}{p}\frac{d}{n}\right)^{-1}.$$
Following the same procedure as @Boddle suggests, but without multiplying through by $2^n$, we obtain the following equation
$$-\left(\frac{d}{n}+\frac{1}{2n}\right)\log\left(\frac{d}{n}\right)
-\left(1-\frac{d}{n}-\frac{1}{2n}\right)\log\left(1-\frac{d}{n}\right)
-\frac{1}{n}\log\left(1-\frac{1}{p}\frac{d}{n}\right)
+\left(\frac{d}{n}+\frac{1}{2n}\right)\log\left(\frac{p}{1-p}\right) =
-\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n)\right).$$
Again defining $\nu = \frac{d}{n} + \frac{1}{2n}$, we obtain an equation of which the solution can be found numerically
$$-\nu\log(\nu) - (1-\nu)\log(1-\nu) -\frac{1}{n}\log(1-\nu/p) + \nu\log\left(\frac{p}{1-p}\right) \\
= -\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n)\right).$$
Again, it is clear that the value of $\nu$ depends only on the ratio $\frac{m}{n}$ for large $n$. From the solution of the equation above, we can get to the value of $d$ and $\hat{d}$ and finally we define $\hat{\lambda} = \frac{p}{1-p}\frac{n-\hat{d}}{\hat{d}}$. From here on, the solution is as explained by @Boddle with this change of definition.
It is also useful to give the solution in the case $k \sim \gamma 2^m$, where $\gamma > 0$. We need to find $d$ such that $\mathbb{P}(X_i \leq d) \approx \frac{2^{-m}}{\gamma}$ to maintain $\mathbb{P}(\min X_i > d) \approx e^{-1}$. We can see that nothing changes, except that the equation to solve numerically now becomes
$$-\nu\log(\nu) - (1-\nu)\log(1-\nu) -\frac{1}{n}\log(1-\nu/p) + \nu\log\left(\frac{p}{1-p}\right) \\
= -\log(1-p) -\frac{m}{n}\log(2)
+\frac{1}{2n} \left(\log\left(\frac{p}{1-p}\right) + \log(2\pi n) + 2\log(\gamma)\right).$$
For large $n$, the difference becomes negligible and the solution is approximately the same as above.
I computed the values of $d/n$ as a function of $m/n$ for infinitely large $n$ using the equations above. I show the curves on the plot below for different values of $p \geq 1/2$. This gives an idea of the expected value of the minimum as $k=2^m$ increases relative to m. | Asymptotic distribution of the max (min) of IID binomial variables
Since the answer of @Boddle does not give the detail for the case $p \neq 1/2$, I will provide it here.
First off, the geometric approximation still holds for $n \gg d \gg 1$. For $j \geq 0$ we obtain |
38,763 | R t.test ..... NOT significant anymore | The standard deviation that comes into the denominator also affected by the outlying observation. (It also affects the degrees of freedom because we are actually doing a Welch test here.)
We can examine the influence of changes in that additional observation on the t-statistic:
tinfl <- function(x) t.test(1:10, y = c(7:20, x))$statistic
(or the p-value tinflp <- function(x) t.test(1:10, y = c(7:20, x))$p.value).
[Adding an observation near 10.18855 leaves the test statistic about where it was without the additional observation (an observation near 9.666492 leaves the p-value where it was).]
This is called an empirical influence function. It's useful for seeing how statistics respond to moving a data point.
So here's what happens to the numerator, denominator and value of the t-statistic as we vary that additional observation:
The red dashed line marks what happens when the additional observation is 10 (somewhere close to where it needs to be to get either the same test statistic or the same p-value as without the observation).
As you move the additional observation up from that, the t-statistic becomes more and more negative (more significant) until you hit about -17.25, and then the effect on the standard deviation (and to some extent the d.f.) starts pulling it back.
As $x\to\infty$, the test statistic goes to -1.
(the limit as $x\to -\infty$ is 1)
You see similar effects with the equal-variance two-sample t-test as well.
The t-test is not particularly robust to very large outliers.
If you had two processes you were interested in identifying location differences in, but there was rare contamination by extreme outliers (from some additional process which was not of interest in the things you wanted to compare with the test), you could robustify the t-test (by modifying the influence function of both numerator and denominator so that they're both bounded), or consider say a Wilcoxon-Mann-Whitney test, so that the effect of the extra observation is more like what you might expect. Or you might consider a permutation test (whether with a robust statistic or not).
Here's the effect on the Wilcoxon-Mann-Whitney test, and a particular form of robustified t-test for comparison - as you see, the Wilcoxon statistic is monotonic, while the robustified t-test only comes back slightly.
$\hspace{1.5cm}$ | R t.test ..... NOT significant anymore | The standard deviation that comes into the denominator also affected by the outlying observation. (It also affects the degrees of freedom because we are actually doing a Welch test here.)
We can exam | R t.test ..... NOT significant anymore
The standard deviation that comes into the denominator also affected by the outlying observation. (It also affects the degrees of freedom because we are actually doing a Welch test here.)
We can examine the influence of changes in that additional observation on the t-statistic:
tinfl <- function(x) t.test(1:10, y = c(7:20, x))$statistic
(or the p-value tinflp <- function(x) t.test(1:10, y = c(7:20, x))$p.value).
[Adding an observation near 10.18855 leaves the test statistic about where it was without the additional observation (an observation near 9.666492 leaves the p-value where it was).]
This is called an empirical influence function. It's useful for seeing how statistics respond to moving a data point.
So here's what happens to the numerator, denominator and value of the t-statistic as we vary that additional observation:
The red dashed line marks what happens when the additional observation is 10 (somewhere close to where it needs to be to get either the same test statistic or the same p-value as without the observation).
As you move the additional observation up from that, the t-statistic becomes more and more negative (more significant) until you hit about -17.25, and then the effect on the standard deviation (and to some extent the d.f.) starts pulling it back.
As $x\to\infty$, the test statistic goes to -1.
(the limit as $x\to -\infty$ is 1)
You see similar effects with the equal-variance two-sample t-test as well.
The t-test is not particularly robust to very large outliers.
If you had two processes you were interested in identifying location differences in, but there was rare contamination by extreme outliers (from some additional process which was not of interest in the things you wanted to compare with the test), you could robustify the t-test (by modifying the influence function of both numerator and denominator so that they're both bounded), or consider say a Wilcoxon-Mann-Whitney test, so that the effect of the extra observation is more like what you might expect. Or you might consider a permutation test (whether with a robust statistic or not).
Here's the effect on the Wilcoxon-Mann-Whitney test, and a particular form of robustified t-test for comparison - as you see, the Wilcoxon statistic is monotonic, while the robustified t-test only comes back slightly.
$\hspace{1.5cm}$ | R t.test ..... NOT significant anymore
The standard deviation that comes into the denominator also affected by the outlying observation. (It also affects the degrees of freedom because we are actually doing a Welch test here.)
We can exam |
38,764 | R t.test ..... NOT significant anymore | The two-group t-test balances (by computing their ratios) two aspects of the distributions of the values, one: the difference in the means, which your "disturbance" did increase somewhat, and two: the variance which your disturbance increases much more. The variance varies with the square of the differences of the point values from the mean and your single extra value that was hundreds of units from the mean would have added something on the order of 180^2 to the variance estimate where it had been much smaller. Under the hypothesis of normally distributed values (which your alteration has massively violated), the variance is now much larger and the estimate of the difference in group means now plausibly includes zero.
If you want to use a test statistic that does not depend on squared deviations, consider the ks.test:
ks.test(1:10, y = c(7:20, 200))
#-------------------------
Two-sample Kolmogorov-Smirnov test
data: 1:10 and c(7:20, 200)
D = 0.7333, p-value = 0.003151
alternative hypothesis: two-sided
Warning message:
In ks.test(1:10, y = c(7:20, 200)) : cannot compute exact p-value with ties
As became clear in my correspondence with Glen_b I was conflating the wilcox.test in R with the ks.test in R. I meant to use the the wilcox.test (Wilcoxon Rank Sum test):
> wilcox.test(1:10, y = c(7:20, 200))
Wilcoxon rank sum test with continuity correction
data: 1:10 and c(7:20, 200)
W = 8, p-value = 0.0002229
alternative hypothesis: true location shift is not equal to 0
Warning message:
In wilcox.test.default(1:10, y = c(7:20, 200)) :
cannot compute exact p-value with ties | R t.test ..... NOT significant anymore | The two-group t-test balances (by computing their ratios) two aspects of the distributions of the values, one: the difference in the means, which your "disturbance" did increase somewhat, and two: the | R t.test ..... NOT significant anymore
The two-group t-test balances (by computing their ratios) two aspects of the distributions of the values, one: the difference in the means, which your "disturbance" did increase somewhat, and two: the variance which your disturbance increases much more. The variance varies with the square of the differences of the point values from the mean and your single extra value that was hundreds of units from the mean would have added something on the order of 180^2 to the variance estimate where it had been much smaller. Under the hypothesis of normally distributed values (which your alteration has massively violated), the variance is now much larger and the estimate of the difference in group means now plausibly includes zero.
If you want to use a test statistic that does not depend on squared deviations, consider the ks.test:
ks.test(1:10, y = c(7:20, 200))
#-------------------------
Two-sample Kolmogorov-Smirnov test
data: 1:10 and c(7:20, 200)
D = 0.7333, p-value = 0.003151
alternative hypothesis: two-sided
Warning message:
In ks.test(1:10, y = c(7:20, 200)) : cannot compute exact p-value with ties
As became clear in my correspondence with Glen_b I was conflating the wilcox.test in R with the ks.test in R. I meant to use the the wilcox.test (Wilcoxon Rank Sum test):
> wilcox.test(1:10, y = c(7:20, 200))
Wilcoxon rank sum test with continuity correction
data: 1:10 and c(7:20, 200)
W = 8, p-value = 0.0002229
alternative hypothesis: true location shift is not equal to 0
Warning message:
In wilcox.test.default(1:10, y = c(7:20, 200)) :
cannot compute exact p-value with ties | R t.test ..... NOT significant anymore
The two-group t-test balances (by computing their ratios) two aspects of the distributions of the values, one: the difference in the means, which your "disturbance" did increase somewhat, and two: the |
38,765 | Linear Regression makes impossible predictions | It's not the predictors (IVs) that are the problem, but the analysis.
Indeed, the mere existence of an impossible part of the range of the response (you can't have negative prices) would be a hint to consider something other than multiple regression (at least on the untransformed variable) - since it clearly can have negative predictions.
There are a number of ways of dealing with non-negative variables, but two fairly simple approaches might be worth considering:
modelling log-price; this is a common strategy with price-like variables in economics
using generalized linear models (GLMs). A gamma-model with a log-link would be quite similar to modelling log-price, but the model would be for the expected price rather than expected log-price. This may have some advantages. If you need the relationship with the predictors to be linear in actual price, this can be done (identity link), but a log link for this sort of data would be more common.
As Bill mentions in comments, there's an issue with log-price when you transform back to original units - you no longer have a model for the expectation, but for the median. That said, if you assume normality on the log-scale you can easily compute an ML or MOM estimate of the mean on the original scale.
(And if you can't assume normality on the log-scale you can still approximate the expectation on the original scale via a Taylor expansion.)
Prediction intervals for a new observation, however, transform just fine. | Linear Regression makes impossible predictions | It's not the predictors (IVs) that are the problem, but the analysis.
Indeed, the mere existence of an impossible part of the range of the response (you can't have negative prices) would be a hint to | Linear Regression makes impossible predictions
It's not the predictors (IVs) that are the problem, but the analysis.
Indeed, the mere existence of an impossible part of the range of the response (you can't have negative prices) would be a hint to consider something other than multiple regression (at least on the untransformed variable) - since it clearly can have negative predictions.
There are a number of ways of dealing with non-negative variables, but two fairly simple approaches might be worth considering:
modelling log-price; this is a common strategy with price-like variables in economics
using generalized linear models (GLMs). A gamma-model with a log-link would be quite similar to modelling log-price, but the model would be for the expected price rather than expected log-price. This may have some advantages. If you need the relationship with the predictors to be linear in actual price, this can be done (identity link), but a log link for this sort of data would be more common.
As Bill mentions in comments, there's an issue with log-price when you transform back to original units - you no longer have a model for the expectation, but for the median. That said, if you assume normality on the log-scale you can easily compute an ML or MOM estimate of the mean on the original scale.
(And if you can't assume normality on the log-scale you can still approximate the expectation on the original scale via a Taylor expansion.)
Prediction intervals for a new observation, however, transform just fine. | Linear Regression makes impossible predictions
It's not the predictors (IVs) that are the problem, but the analysis.
Indeed, the mere existence of an impossible part of the range of the response (you can't have negative prices) would be a hint to |
38,766 | Linear Regression makes impossible predictions | One option would be to fit a generalized linear model with a different reference distribution that is bounded at zero (and probably more appropriate than the normal distribution, depending on what kind of prices you're modeling). For example, the negative binomial distribution suits discrete distributions of counts; this could work if your data are whole numbers representing counts of currency units. The gamma distribution is a continuous alternative (with an otherwise similar shape) that may be more suitable, as it's much more commonly used for financial data (see "Real-life examples of common distributions").
Negative predictions do not reflect badly on the utility of your predictors. | Linear Regression makes impossible predictions | One option would be to fit a generalized linear model with a different reference distribution that is bounded at zero (and probably more appropriate than the normal distribution, depending on what kin | Linear Regression makes impossible predictions
One option would be to fit a generalized linear model with a different reference distribution that is bounded at zero (and probably more appropriate than the normal distribution, depending on what kind of prices you're modeling). For example, the negative binomial distribution suits discrete distributions of counts; this could work if your data are whole numbers representing counts of currency units. The gamma distribution is a continuous alternative (with an otherwise similar shape) that may be more suitable, as it's much more commonly used for financial data (see "Real-life examples of common distributions").
Negative predictions do not reflect badly on the utility of your predictors. | Linear Regression makes impossible predictions
One option would be to fit a generalized linear model with a different reference distribution that is bounded at zero (and probably more appropriate than the normal distribution, depending on what kin |
38,767 | What could be a statistical test for comparing funnel data before and after important changes? | Caveats
Most importantly, a lot of things could have changed since you made the upgrade. For instance, if a major competitor went out of business and Christmas rolled around in time for the change, your test will be conflating the positive effect of those factors with the site improvements. They could even mask that the new version is bad. It would have been a much better experimental design to split some fraction of your site traffic into the new version at random, and then compare the outcomes for those who saw the new and the old site during the same period. This holds seasonality and competition constant, so you're not comparing apples to orangutans. Not a whole lot can be done to address this (at least with the data you provided).
We are also going to assume that customers do not interact with each other (stockouts aren't possible, for instance) and that there are no repeat visits. We also assume that people can't skip steps in the funnel and that they can't enter the funnel anywhere but the beginning. These might be unrealistic assumptions for some web sites, but relaxing them complicates things.
Model and Data Transformations
If you are willing to ignore these concerns, you might try using a sequential logit model to analyze the flow through the funnel. This approach is sometimes called the sequential response model, continuation ratio logit, model for nested dichotomies, or the Mare model (after the UCLA sociologist). It has more names than an identity fraudster!
This approach requires data at individual customer level, which I can back out from the table you provided by differencing. This will handle the fact that traffic is higher on the new site. I will be using Stata and Maarten Buis' seqlogit command. Some part of this can be handled with a series of logit commands* (which any advanced statistical software should be able to handle), but seqlogit allows you to do a very cool "decomposition" of the total effect of the version on the final outcome (like purchase probability or even a dollar amount).
I've already changed your data from a Napoleon's Campaign format to final outcome by differencing adjacent cells along each column:
. /* Set Up The Data */
. set more off
. clear
. input str10 finstat byte version int n
finstat version n
1. "Browsed" 1 89
2. "Clicked" 1 3
3. "Step3" 1 1
4. "Step4" 1 2
5. "Step5" 1 7
6. "Purchased" 1 19
7. "Browsed" 2 937
8. "Clicked" 2 21
9. "Step3" 2 5
10. "Step4" 2 15
11. "Step5" 2 26
12. "Purchased" 2 345
13. end
. sencode finstat, replace
. lab define version 1 "Old" 2 "New"
. lab val version version
. expand n
(1458 observations created)
. sort version finstat
. drop n
This gives us 1470 observations/rows (I could have also used frequency weights instead of expanding the data). For instance, for the Old version, we have 89 people who only browsed and 19 who completed a purchase and 13 who dropped out somewhere in between.
. tab finstat version
| version
finstat | Old New | Total
-----------+----------------------+----------
Browsed | 89 937 | 1,026
Clicked | 3 21 | 24
Step3 | 1 5 | 6
Step4 | 2 15 | 17
Step5 | 7 26 | 33
Purchased | 19 345 | 364
-----------+----------------------+----------
Total | 121 1,349 | 1,470
Sequential Logit For Each Step In The Order Funnel
Now we fit the sequential logit of final outcome on binary version. The tree() option specifies the structure of the decision tree (the choices available at the $6$ junctures), and the levels() option specifies the revenue effects of stopping at each stage. Here I assume you only care about the completed purchase. This assumption does not alter the estimation, but will be used in the decomposition. The estimates are:
. /* Sequential Logit */
. seqlogit finstat i.version, ///
> tree(1: 2 3 4 5 6, 2: 3 4 5 6, 3: 4 5 6, 4: 5 6, 5: 6) ///
> levels(1=0,2=0,3=0,4=0,5=0,6=1) ///
> or robust ///
>
Transition tree:
Transition 1: 1 : 2 3 4 5 6
Transition 2: 2 : 3 4 5 6
Transition 3: 3 : 4 5 6
Transition 4: 4 : 5 6
Transition 5: 5 : 6
Computing starting values for:
Transition 1
Transition 2
Transition 3
Transition 4
Transition 5
Iteration 0: log pseudolikelihood = -1204.027
Iteration 1: log pseudolikelihood = -1204.027
Number of obs = 1470
Wald chi2(1) = 0.88
Log pseudolikelihood = -1204.027 Prob > chi2 = 0.3482
------------------------------------------------------------------------------
| Robust
finstat | Odds Ratio Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
_2_3_4_5_6v1 |
version |
New | 1.222919 .2623202 0.94 0.348 .8031785 1.862015
_cons | .3595506 .0741362 -4.96 0.000 .2400212 .538605
-------------+----------------------------------------------------------------
_3_4_5_6v2 |
version |
New | 1.926108 1.245698 1.01 0.311 .5422151 6.842106
_cons | 9.666667 5.86462 3.74 0.000 2.943511 31.74591
-------------+----------------------------------------------------------------
_4_5_6v3 |
version |
New | 2.757144 3.069166 0.91 0.362 .3111206 24.43376
_cons | 27.99999 28.50525 3.27 0.001 3.807117 205.9299
-------------+----------------------------------------------------------------
_5_6v4 |
version |
New | 1.902564 1.483801 0.82 0.410 .412564 8.773792
_cons | 13 9.542633 3.49 0.000 3.08404 54.79825
-------------+----------------------------------------------------------------
_6v5 |
version |
New | 4.888664 2.379981 3.26 0.001 1.882756 12.69365
_cons | 2.714286 1.200506 2.26 0.024 1.140713 6.458546
------------------------------------------------------------------------------
For each step in the funnel, we have a logit model where the estimated coefficients are transformed to odds ratios. For example, the first choice is whether to just browse (1) or continue further into the funnel (2-6). The baseline odds given by the _cons coefficient, which corresponds to the old version of the site, are $0.3595506$. This means that a lot of people drop out at this stage on the old site: roughly one third of a customer goes further for every person who merely window shops (or one for every three if the concept of fractional people conjures troubling visions of amputees). This is equivalent to the raw numbers of $(19+13)/89$.
The New coefficient gives you the multiplicative effect on the baseline odds. It's $1.222919$, so that's $22\%$ increase in the odds of continuing. So for the new site, the odds should be $1.222919 \cdot 0.3595506=0.43970126$, which matches the actual data of $(67+345)/937=0.4397$ quite nicely since we have no covariates. On the new site, almost half a user moves on past the just browsing stage. Time to get your developers some pizza and a case of beer.
However, the p-value is $0.348$ and the $95\%$ Confidence interval is $[.8031785,1.862015]$, which includes $1$. Containing 1 is unfortunate because multiplying by one leaves the baseline unchanged; less than one means the new version is worse. This means that the apparent improvement over the old site is not statistically significant, at least for this stage in the oder flow. In other words, it could be real or it could be luck. If we had more data (larger sample for the old site), we might have been able to tell the difference. You might also consider adding demographic and behavioral data (or even your segments) about your customers to this type of model as covariates. It may help with the significance.
If we look at the remaining decision stages, we see the multiplicative effects on the baseline odds are typically greater than 1, but are usually insignificant. The last stage (Drop Out at Step $5$ or Complete Purchase) has a whopping multiplicative effect of $4.888664$ with a p-value of $0.024$. Since this is the one stage that puts money in the bank, a significant increase by a factor of almost $5$ is terrific.
Calculating The Total Effect
Now we move on to the decomposition:
. /* Decomposition */
. seqlogitdecomp version, table marg
At:
variable | value
-------------+---------
version | 1
Decomposition:
| _2_3_4_5_6v1 | _3_4_5_6v2 | _4_5_6v3 | _5_6v4 | _6v5
| b se | b se | b se | b se | b se
-------------+------------------+------------------+------------------+------------------+------------------
trans | | | | |
1b.version | 0 . | 0 . | 0 . | 0 . | 0 .
2.version | .0409 .042 | .0428 .0527 | .0217 .0344 | .0326 .0497 | .199 .088
-------------+------------------+------------------+------------------+------------------+------------------
weight | | | | |
weight | .594 .0868 | .173 .0351 | .163 .0338 | .169 .0345 | .215 .0373
at risk | 1 . | .264 .0401 | .24 .0388 | .231 .0383 | .215 .0373
gain | .594 .0868 | .655 .0883 | .679 .0883 | .731 .087 | 1 .
-------------+------------------+------------------+------------------+------------------+------------------
pr(pass) | | | | |
pr | .264 .0401 | .906 .0515 | .966 .0339 | .929 .0487 | .731 .087
-------------+------------------+------------------+------------------+------------------+------------------
tot | | | | |
1b.version | 0 . | | | |
2.version | .0987 .0329 | | | |
The first rows gives the effects in the standard additive probability metric (with the marg option). For me, this is easier to think about than the log odds ratio or the logit scale. For example, for the first stage, the New version effect is $0.0409$ with a standard error of $0.042$. This means a customer who encountered the new version is $4.1$ percentage points more likely to move to the add to cart stage and beyond compared to the old site.
You can use the standard error to construct your own $95\%$ confidence interval $[b\pm 1.96 \cdot se]=[-0.04142,0.12322]$, which unfortunately includes zero. You also have the effects for the other stages. The results are very similar to what we saw with multiplicative OR coefficients: only the last transition shows a significant effect (confidence interval does not include zero, since we're adding now rather than multiplying). The effect is an additional $19.9\%$, which is pretty close to $22\%$ we saw above.
The cool part is the very last row. It gives you the total effect on the probability of order completion given the effect of version on all the intermediate stages. Amazingly, this is a weighted sum of the marginal effects on each transition, where the weights are the product of two elements: the proportion "at risk", and the expected gain from passing. The first proportion is $1$, since everyone can pass from the browsing state. It gets smaller with each stage as people drop out. This makes sense: if you improve the last stage a great deal, but no one makes it there to appreciate it, you're not going to get a whole lot of a lift.
The gain line is a bit more confusing. We've assumed that you only care about the final step (the levels() in the seqlogit command assigned zero weights to all others). This means that the gain for the last stage is 1. For the first stage, we know that if someone doesn't drop out after browsing, his expected purchase probability is $0.906 \cdot 0.966 \cdot 0.929 \cdot 0.731 \cdot 1 = 0.594$. This is just the product of the probabilities of passing each stage, which compound. The probabilities are given by the pr(pass) line. For example, the first one is $(3+1+2+7+19)/121=0.264$
Then the marginal effect is
$$\frac{\Delta \mathbf{Pr} (P=1)}{\Delta v}=\sum_{s=1}^6 r_s \cdot g_s \cdot m_s, $$
where $r_s$ is the fraction at risk at stage $s$, $g_s$ is the expected gain at stage $s$, and $m_s$ is the marginal effect on stage $s$.
Now we get all the pieces, we can do the calculation
$$1\cdot.594\cdot.0409 + .264\cdot.655\cdot.0428 + .24\cdot.679\cdot.0217 + .231\cdot.731\cdot.0326+.215\cdot 1 \cdot .199=.0836$$
This doesn't quite match the total effect in the output for some reason. I thought it was most likely due to rounding error, but that does not seem to be the case. I will report back once I figure it out.
The total treatment effect in the table is $0.0987$ with a standard error of $0.033$. This means the $95\%$ confidence interval is $[0.03402,0.16338]$. That's a $10$ percentage point improvement in order completion over the old version (definitely economically significant), which also looks statistically significant (it ain't just luck). This is the one number you can show to the CFO who doesn't care about all the technical and statistical details. You can read more about how to derive this on Maarten Buis' site while the pizza and beer are being delivered.
Another nice calculation you can do is the revenue effect. You can either change the levels() option for the final stage from $1$ to the (average) price of your product or do it manually like this. If the price of your item was $\$100$ dollars and dropping out at earlier stages has no benefit for you, then your lift is worth an incremental $\$9.87$ per customer who made it to the product page.
You can also specify the benefits to you of dropping out at earlier stages (if Step 5 was worth only \$4 and purchase is worth \$100) the total effect is now only 9.72 since the new version makes attrition at the earlier stage less likely, which now carries a probabilistic cost of loosing $\$4$ dollars. This makes it easy to model upgrades.
*Here's how you replicate the Step 4 versus Step5 or Purchase of the sequential logit with a lone logit:
. recode finstat 1/3=. 4=0 5=1 6=1, gen(x)
(1470 differences between finstat and x)
. logit x i.version, or robust nolog
Logistic regression Number of obs = 414
Wald chi2(1) = 0.68
Prob > chi2 = 0.4099
Log pseudolikelihood = -70.626428 Pseudo R2 = 0.0042
------------------------------------------------------------------------------
| Robust
x | Odds Ratio Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
version |
New | 1.902564 1.485092 0.82 0.410 .4120157 8.785467
_cons | 13 9.550934 3.49 0.000 3.080183 54.86688
------------------------------------------------------------------------------
. margins, dydx(version)
Conditional marginal effects Number of obs = 414
Model VCE : Robust
Expression : Pr(x), predict()
dy/dx w.r.t. : 2.version
------------------------------------------------------------------------------
| Delta-method
| dy/dx Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
version |
New | .0325685 .0497145 0.66 0.512 -.0648703 .1300072
------------------------------------------------------------------------------
Note: dy/dx for factor levels is the discrete change from the base level.
Note how this matches the OR and decomposition coefficients, respectively. The really hard part of using the sequence of logits will be getting the right standard errors for the total effect. Perhaps you can estimate all the marginal effects equations simultaneously and then calculate their weighted linear combination as above.
The Appendix of Alan Agresti's Analysis of Ordinal Categorical Data discusses various software implementations, though he calls it a continuation ratio logit. | What could be a statistical test for comparing funnel data before and after important changes? | Caveats
Most importantly, a lot of things could have changed since you made the upgrade. For instance, if a major competitor went out of business and Christmas rolled around in time for the change, yo | What could be a statistical test for comparing funnel data before and after important changes?
Caveats
Most importantly, a lot of things could have changed since you made the upgrade. For instance, if a major competitor went out of business and Christmas rolled around in time for the change, your test will be conflating the positive effect of those factors with the site improvements. They could even mask that the new version is bad. It would have been a much better experimental design to split some fraction of your site traffic into the new version at random, and then compare the outcomes for those who saw the new and the old site during the same period. This holds seasonality and competition constant, so you're not comparing apples to orangutans. Not a whole lot can be done to address this (at least with the data you provided).
We are also going to assume that customers do not interact with each other (stockouts aren't possible, for instance) and that there are no repeat visits. We also assume that people can't skip steps in the funnel and that they can't enter the funnel anywhere but the beginning. These might be unrealistic assumptions for some web sites, but relaxing them complicates things.
Model and Data Transformations
If you are willing to ignore these concerns, you might try using a sequential logit model to analyze the flow through the funnel. This approach is sometimes called the sequential response model, continuation ratio logit, model for nested dichotomies, or the Mare model (after the UCLA sociologist). It has more names than an identity fraudster!
This approach requires data at individual customer level, which I can back out from the table you provided by differencing. This will handle the fact that traffic is higher on the new site. I will be using Stata and Maarten Buis' seqlogit command. Some part of this can be handled with a series of logit commands* (which any advanced statistical software should be able to handle), but seqlogit allows you to do a very cool "decomposition" of the total effect of the version on the final outcome (like purchase probability or even a dollar amount).
I've already changed your data from a Napoleon's Campaign format to final outcome by differencing adjacent cells along each column:
. /* Set Up The Data */
. set more off
. clear
. input str10 finstat byte version int n
finstat version n
1. "Browsed" 1 89
2. "Clicked" 1 3
3. "Step3" 1 1
4. "Step4" 1 2
5. "Step5" 1 7
6. "Purchased" 1 19
7. "Browsed" 2 937
8. "Clicked" 2 21
9. "Step3" 2 5
10. "Step4" 2 15
11. "Step5" 2 26
12. "Purchased" 2 345
13. end
. sencode finstat, replace
. lab define version 1 "Old" 2 "New"
. lab val version version
. expand n
(1458 observations created)
. sort version finstat
. drop n
This gives us 1470 observations/rows (I could have also used frequency weights instead of expanding the data). For instance, for the Old version, we have 89 people who only browsed and 19 who completed a purchase and 13 who dropped out somewhere in between.
. tab finstat version
| version
finstat | Old New | Total
-----------+----------------------+----------
Browsed | 89 937 | 1,026
Clicked | 3 21 | 24
Step3 | 1 5 | 6
Step4 | 2 15 | 17
Step5 | 7 26 | 33
Purchased | 19 345 | 364
-----------+----------------------+----------
Total | 121 1,349 | 1,470
Sequential Logit For Each Step In The Order Funnel
Now we fit the sequential logit of final outcome on binary version. The tree() option specifies the structure of the decision tree (the choices available at the $6$ junctures), and the levels() option specifies the revenue effects of stopping at each stage. Here I assume you only care about the completed purchase. This assumption does not alter the estimation, but will be used in the decomposition. The estimates are:
. /* Sequential Logit */
. seqlogit finstat i.version, ///
> tree(1: 2 3 4 5 6, 2: 3 4 5 6, 3: 4 5 6, 4: 5 6, 5: 6) ///
> levels(1=0,2=0,3=0,4=0,5=0,6=1) ///
> or robust ///
>
Transition tree:
Transition 1: 1 : 2 3 4 5 6
Transition 2: 2 : 3 4 5 6
Transition 3: 3 : 4 5 6
Transition 4: 4 : 5 6
Transition 5: 5 : 6
Computing starting values for:
Transition 1
Transition 2
Transition 3
Transition 4
Transition 5
Iteration 0: log pseudolikelihood = -1204.027
Iteration 1: log pseudolikelihood = -1204.027
Number of obs = 1470
Wald chi2(1) = 0.88
Log pseudolikelihood = -1204.027 Prob > chi2 = 0.3482
------------------------------------------------------------------------------
| Robust
finstat | Odds Ratio Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
_2_3_4_5_6v1 |
version |
New | 1.222919 .2623202 0.94 0.348 .8031785 1.862015
_cons | .3595506 .0741362 -4.96 0.000 .2400212 .538605
-------------+----------------------------------------------------------------
_3_4_5_6v2 |
version |
New | 1.926108 1.245698 1.01 0.311 .5422151 6.842106
_cons | 9.666667 5.86462 3.74 0.000 2.943511 31.74591
-------------+----------------------------------------------------------------
_4_5_6v3 |
version |
New | 2.757144 3.069166 0.91 0.362 .3111206 24.43376
_cons | 27.99999 28.50525 3.27 0.001 3.807117 205.9299
-------------+----------------------------------------------------------------
_5_6v4 |
version |
New | 1.902564 1.483801 0.82 0.410 .412564 8.773792
_cons | 13 9.542633 3.49 0.000 3.08404 54.79825
-------------+----------------------------------------------------------------
_6v5 |
version |
New | 4.888664 2.379981 3.26 0.001 1.882756 12.69365
_cons | 2.714286 1.200506 2.26 0.024 1.140713 6.458546
------------------------------------------------------------------------------
For each step in the funnel, we have a logit model where the estimated coefficients are transformed to odds ratios. For example, the first choice is whether to just browse (1) or continue further into the funnel (2-6). The baseline odds given by the _cons coefficient, which corresponds to the old version of the site, are $0.3595506$. This means that a lot of people drop out at this stage on the old site: roughly one third of a customer goes further for every person who merely window shops (or one for every three if the concept of fractional people conjures troubling visions of amputees). This is equivalent to the raw numbers of $(19+13)/89$.
The New coefficient gives you the multiplicative effect on the baseline odds. It's $1.222919$, so that's $22\%$ increase in the odds of continuing. So for the new site, the odds should be $1.222919 \cdot 0.3595506=0.43970126$, which matches the actual data of $(67+345)/937=0.4397$ quite nicely since we have no covariates. On the new site, almost half a user moves on past the just browsing stage. Time to get your developers some pizza and a case of beer.
However, the p-value is $0.348$ and the $95\%$ Confidence interval is $[.8031785,1.862015]$, which includes $1$. Containing 1 is unfortunate because multiplying by one leaves the baseline unchanged; less than one means the new version is worse. This means that the apparent improvement over the old site is not statistically significant, at least for this stage in the oder flow. In other words, it could be real or it could be luck. If we had more data (larger sample for the old site), we might have been able to tell the difference. You might also consider adding demographic and behavioral data (or even your segments) about your customers to this type of model as covariates. It may help with the significance.
If we look at the remaining decision stages, we see the multiplicative effects on the baseline odds are typically greater than 1, but are usually insignificant. The last stage (Drop Out at Step $5$ or Complete Purchase) has a whopping multiplicative effect of $4.888664$ with a p-value of $0.024$. Since this is the one stage that puts money in the bank, a significant increase by a factor of almost $5$ is terrific.
Calculating The Total Effect
Now we move on to the decomposition:
. /* Decomposition */
. seqlogitdecomp version, table marg
At:
variable | value
-------------+---------
version | 1
Decomposition:
| _2_3_4_5_6v1 | _3_4_5_6v2 | _4_5_6v3 | _5_6v4 | _6v5
| b se | b se | b se | b se | b se
-------------+------------------+------------------+------------------+------------------+------------------
trans | | | | |
1b.version | 0 . | 0 . | 0 . | 0 . | 0 .
2.version | .0409 .042 | .0428 .0527 | .0217 .0344 | .0326 .0497 | .199 .088
-------------+------------------+------------------+------------------+------------------+------------------
weight | | | | |
weight | .594 .0868 | .173 .0351 | .163 .0338 | .169 .0345 | .215 .0373
at risk | 1 . | .264 .0401 | .24 .0388 | .231 .0383 | .215 .0373
gain | .594 .0868 | .655 .0883 | .679 .0883 | .731 .087 | 1 .
-------------+------------------+------------------+------------------+------------------+------------------
pr(pass) | | | | |
pr | .264 .0401 | .906 .0515 | .966 .0339 | .929 .0487 | .731 .087
-------------+------------------+------------------+------------------+------------------+------------------
tot | | | | |
1b.version | 0 . | | | |
2.version | .0987 .0329 | | | |
The first rows gives the effects in the standard additive probability metric (with the marg option). For me, this is easier to think about than the log odds ratio or the logit scale. For example, for the first stage, the New version effect is $0.0409$ with a standard error of $0.042$. This means a customer who encountered the new version is $4.1$ percentage points more likely to move to the add to cart stage and beyond compared to the old site.
You can use the standard error to construct your own $95\%$ confidence interval $[b\pm 1.96 \cdot se]=[-0.04142,0.12322]$, which unfortunately includes zero. You also have the effects for the other stages. The results are very similar to what we saw with multiplicative OR coefficients: only the last transition shows a significant effect (confidence interval does not include zero, since we're adding now rather than multiplying). The effect is an additional $19.9\%$, which is pretty close to $22\%$ we saw above.
The cool part is the very last row. It gives you the total effect on the probability of order completion given the effect of version on all the intermediate stages. Amazingly, this is a weighted sum of the marginal effects on each transition, where the weights are the product of two elements: the proportion "at risk", and the expected gain from passing. The first proportion is $1$, since everyone can pass from the browsing state. It gets smaller with each stage as people drop out. This makes sense: if you improve the last stage a great deal, but no one makes it there to appreciate it, you're not going to get a whole lot of a lift.
The gain line is a bit more confusing. We've assumed that you only care about the final step (the levels() in the seqlogit command assigned zero weights to all others). This means that the gain for the last stage is 1. For the first stage, we know that if someone doesn't drop out after browsing, his expected purchase probability is $0.906 \cdot 0.966 \cdot 0.929 \cdot 0.731 \cdot 1 = 0.594$. This is just the product of the probabilities of passing each stage, which compound. The probabilities are given by the pr(pass) line. For example, the first one is $(3+1+2+7+19)/121=0.264$
Then the marginal effect is
$$\frac{\Delta \mathbf{Pr} (P=1)}{\Delta v}=\sum_{s=1}^6 r_s \cdot g_s \cdot m_s, $$
where $r_s$ is the fraction at risk at stage $s$, $g_s$ is the expected gain at stage $s$, and $m_s$ is the marginal effect on stage $s$.
Now we get all the pieces, we can do the calculation
$$1\cdot.594\cdot.0409 + .264\cdot.655\cdot.0428 + .24\cdot.679\cdot.0217 + .231\cdot.731\cdot.0326+.215\cdot 1 \cdot .199=.0836$$
This doesn't quite match the total effect in the output for some reason. I thought it was most likely due to rounding error, but that does not seem to be the case. I will report back once I figure it out.
The total treatment effect in the table is $0.0987$ with a standard error of $0.033$. This means the $95\%$ confidence interval is $[0.03402,0.16338]$. That's a $10$ percentage point improvement in order completion over the old version (definitely economically significant), which also looks statistically significant (it ain't just luck). This is the one number you can show to the CFO who doesn't care about all the technical and statistical details. You can read more about how to derive this on Maarten Buis' site while the pizza and beer are being delivered.
Another nice calculation you can do is the revenue effect. You can either change the levels() option for the final stage from $1$ to the (average) price of your product or do it manually like this. If the price of your item was $\$100$ dollars and dropping out at earlier stages has no benefit for you, then your lift is worth an incremental $\$9.87$ per customer who made it to the product page.
You can also specify the benefits to you of dropping out at earlier stages (if Step 5 was worth only \$4 and purchase is worth \$100) the total effect is now only 9.72 since the new version makes attrition at the earlier stage less likely, which now carries a probabilistic cost of loosing $\$4$ dollars. This makes it easy to model upgrades.
*Here's how you replicate the Step 4 versus Step5 or Purchase of the sequential logit with a lone logit:
. recode finstat 1/3=. 4=0 5=1 6=1, gen(x)
(1470 differences between finstat and x)
. logit x i.version, or robust nolog
Logistic regression Number of obs = 414
Wald chi2(1) = 0.68
Prob > chi2 = 0.4099
Log pseudolikelihood = -70.626428 Pseudo R2 = 0.0042
------------------------------------------------------------------------------
| Robust
x | Odds Ratio Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
version |
New | 1.902564 1.485092 0.82 0.410 .4120157 8.785467
_cons | 13 9.550934 3.49 0.000 3.080183 54.86688
------------------------------------------------------------------------------
. margins, dydx(version)
Conditional marginal effects Number of obs = 414
Model VCE : Robust
Expression : Pr(x), predict()
dy/dx w.r.t. : 2.version
------------------------------------------------------------------------------
| Delta-method
| dy/dx Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
version |
New | .0325685 .0497145 0.66 0.512 -.0648703 .1300072
------------------------------------------------------------------------------
Note: dy/dx for factor levels is the discrete change from the base level.
Note how this matches the OR and decomposition coefficients, respectively. The really hard part of using the sequence of logits will be getting the right standard errors for the total effect. Perhaps you can estimate all the marginal effects equations simultaneously and then calculate their weighted linear combination as above.
The Appendix of Alan Agresti's Analysis of Ordinal Categorical Data discusses various software implementations, though he calls it a continuation ratio logit. | What could be a statistical test for comparing funnel data before and after important changes?
Caveats
Most importantly, a lot of things could have changed since you made the upgrade. For instance, if a major competitor went out of business and Christmas rolled around in time for the change, yo |
38,768 | What could be a statistical test for comparing funnel data before and after important changes? | Considering you have only one realization I would assume the variables to follow a poisson law H0 the values before changes and I would check the after values against the theoretical quantiles under H0 | What could be a statistical test for comparing funnel data before and after important changes? | Considering you have only one realization I would assume the variables to follow a poisson law H0 the values before changes and I would check the after values against the theoretical quantiles under | What could be a statistical test for comparing funnel data before and after important changes?
Considering you have only one realization I would assume the variables to follow a poisson law H0 the values before changes and I would check the after values against the theoretical quantiles under H0 | What could be a statistical test for comparing funnel data before and after important changes?
Considering you have only one realization I would assume the variables to follow a poisson law H0 the values before changes and I would check the after values against the theoretical quantiles under |
38,769 | Forecasting time series regression in R using lm and lag | Estimating with lags and using model for predicting is a sore point in base R. Here is the example:
set.seed(1)
y<-ts(rnorm(10))
x<-ts(rnorm(10))
lm(y~x)
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
0.2006 -0.2749
> lm(y~lag(x))
Call:
lm(formula = y ~ lag(x))
Coefficients:
(Intercept) lag(x)
0.2006 -0.2749
Notice that in both cases the result is the same. This happens because of the somewhat peculiar behaviour of the default lag function. Compare x and lag(x)
x
Time Series:
Start = 1
End = 10
Frequency = 1
[1] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 0.82122120
[10] 0.59390132
> lag(x)
Time Series:
Start = 0
End = 9
Frequency = 1
[1] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 0.82122120
[10] 0.59390132
As you can see the data is the same, only the attributes, in this case the time, are different. Hence the lm sees the same data, since it ignores the attributes. There are several ways of working around this behaviour. Here are few.
First you can convert the data to time series format for which the lag behaviour is "standard". One of such formats is xts from package xts:
yy<-xts(y,as.Date(1:10))
xx<-xts(x,as.Date(1:10))
lm(yy~xx)
Call:
lm(formula = yy ~ lag(xx))
Coefficients:
(Intercept) lag(xx)
0.2754 -0.2798
See now the coefficient is different, since lag now correctly shifts the data:
lag(xx)
[,1]
1970-01-02 NA
1970-01-03 1.51178117
1970-01-04 0.38984324
1970-01-05 -0.62124058
1970-01-06 -2.21469989
1970-01-07 1.12493092
1970-01-08 -0.04493361
1970-01-09 -0.01619026
1970-01-10 0.94383621
1970-01-11 0.82122120
Another way is to estimate the regression using the function dynlm from package dynlm:
dynlm(y~L(x))
Time series regression with "ts" data:
Start = 2, End = 10
Call:
dynlm(formula = y ~ L(x))
Coefficients:
(Intercept) L(x)
0.2754 -0.2798
This covers the estimation. Now predicting is trickier. To get the fitted values you can simply use predict function:
predict(dynlm(y ~ L(x)))
2 3 4 5 6 7 8 9 10
-0.14757748 0.16632219 0.44920672 0.89503027 -0.03934318 0.28796556 0.27992365 0.01132412 0.04562977
predict(lm(yy ~ lag(xx)))
2 3 4 5 6 7 8 9 10
-0.14757748 0.16632219 0.44920672 0.89503027 -0.03934318 0.28796556 0.27992365 0.01132412 0.04562977
Predicting ahead in a future though presents a problem. The default behaviour of predict function is to expect newdata argument. But for one step ahead forecast in this case, no new data is required. So standard predict function will not work in this case. I would love to see a general solution for this problem, but in my knowledge different packages provide different ways of getting such forecasts and if you do not want to write the function yourself you need to cast your model in a form which is required by a specific forecasting function from a specific package. And you need to know that package pretty well.
One of such packages is midasr (of which I am developer). One step ahead forecast for such model would be implemented in the following way:
midas_u(y~mls(x,1,1))
Call:
lm(formula = y ~ mls(x, 1, 1), data = ee)
Coefficients:
(Intercept) mls(x, 1, 1)
0.2754 -0.2798
forecast(midas_u(y~mls(x,1,1)),newdata=list(x=NA))
[1] 0.1092301
The package midasr works with mixed frequency data. The function mls has 3 arguments, data, lag numbers and frequency ratio. In this case the frequency is the same so the third argument is 1. In that case the function works exactly as the function lag for xts objects. For forecasting it is necessary to supply new data. As we do not know it we supply the NA which works in this case, since one-step ahead forecasts in this case needs only the data which we already know.
The last value of x is 0.59390132, so you can check that the result is the correct one directly
> 0.59390132*(-0.2798) +0.2754
[1] 0.1092264
The answer is correct to 4 decimal places, since I used the coefficients with 4 digit accuracy. | Forecasting time series regression in R using lm and lag | Estimating with lags and using model for predicting is a sore point in base R. Here is the example:
set.seed(1)
y<-ts(rnorm(10))
x<-ts(rnorm(10))
lm(y~x)
Call:
lm(formula = y ~ x)
Coefficients:
(Int | Forecasting time series regression in R using lm and lag
Estimating with lags and using model for predicting is a sore point in base R. Here is the example:
set.seed(1)
y<-ts(rnorm(10))
x<-ts(rnorm(10))
lm(y~x)
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
0.2006 -0.2749
> lm(y~lag(x))
Call:
lm(formula = y ~ lag(x))
Coefficients:
(Intercept) lag(x)
0.2006 -0.2749
Notice that in both cases the result is the same. This happens because of the somewhat peculiar behaviour of the default lag function. Compare x and lag(x)
x
Time Series:
Start = 1
End = 10
Frequency = 1
[1] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 0.82122120
[10] 0.59390132
> lag(x)
Time Series:
Start = 0
End = 9
Frequency = 1
[1] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 0.82122120
[10] 0.59390132
As you can see the data is the same, only the attributes, in this case the time, are different. Hence the lm sees the same data, since it ignores the attributes. There are several ways of working around this behaviour. Here are few.
First you can convert the data to time series format for which the lag behaviour is "standard". One of such formats is xts from package xts:
yy<-xts(y,as.Date(1:10))
xx<-xts(x,as.Date(1:10))
lm(yy~xx)
Call:
lm(formula = yy ~ lag(xx))
Coefficients:
(Intercept) lag(xx)
0.2754 -0.2798
See now the coefficient is different, since lag now correctly shifts the data:
lag(xx)
[,1]
1970-01-02 NA
1970-01-03 1.51178117
1970-01-04 0.38984324
1970-01-05 -0.62124058
1970-01-06 -2.21469989
1970-01-07 1.12493092
1970-01-08 -0.04493361
1970-01-09 -0.01619026
1970-01-10 0.94383621
1970-01-11 0.82122120
Another way is to estimate the regression using the function dynlm from package dynlm:
dynlm(y~L(x))
Time series regression with "ts" data:
Start = 2, End = 10
Call:
dynlm(formula = y ~ L(x))
Coefficients:
(Intercept) L(x)
0.2754 -0.2798
This covers the estimation. Now predicting is trickier. To get the fitted values you can simply use predict function:
predict(dynlm(y ~ L(x)))
2 3 4 5 6 7 8 9 10
-0.14757748 0.16632219 0.44920672 0.89503027 -0.03934318 0.28796556 0.27992365 0.01132412 0.04562977
predict(lm(yy ~ lag(xx)))
2 3 4 5 6 7 8 9 10
-0.14757748 0.16632219 0.44920672 0.89503027 -0.03934318 0.28796556 0.27992365 0.01132412 0.04562977
Predicting ahead in a future though presents a problem. The default behaviour of predict function is to expect newdata argument. But for one step ahead forecast in this case, no new data is required. So standard predict function will not work in this case. I would love to see a general solution for this problem, but in my knowledge different packages provide different ways of getting such forecasts and if you do not want to write the function yourself you need to cast your model in a form which is required by a specific forecasting function from a specific package. And you need to know that package pretty well.
One of such packages is midasr (of which I am developer). One step ahead forecast for such model would be implemented in the following way:
midas_u(y~mls(x,1,1))
Call:
lm(formula = y ~ mls(x, 1, 1), data = ee)
Coefficients:
(Intercept) mls(x, 1, 1)
0.2754 -0.2798
forecast(midas_u(y~mls(x,1,1)),newdata=list(x=NA))
[1] 0.1092301
The package midasr works with mixed frequency data. The function mls has 3 arguments, data, lag numbers and frequency ratio. In this case the frequency is the same so the third argument is 1. In that case the function works exactly as the function lag for xts objects. For forecasting it is necessary to supply new data. As we do not know it we supply the NA which works in this case, since one-step ahead forecasts in this case needs only the data which we already know.
The last value of x is 0.59390132, so you can check that the result is the correct one directly
> 0.59390132*(-0.2798) +0.2754
[1] 0.1092264
The answer is correct to 4 decimal places, since I used the coefficients with 4 digit accuracy. | Forecasting time series regression in R using lm and lag
Estimating with lags and using model for predicting is a sore point in base R. Here is the example:
set.seed(1)
y<-ts(rnorm(10))
x<-ts(rnorm(10))
lm(y~x)
Call:
lm(formula = y ~ x)
Coefficients:
(Int |
38,770 | How to calculate the probability of matching sock from a drawer? [closed] | Here are all the different ways of pairing one sock with another different one, arranged systematically:
"Random" in this context means that each pairing is equally likely. Therefore, to find the probability of a color match, count the color-matched pairs and divide by the total.
Counting is made easier by noting that the color-matched socks occur within squares of $6$ by $6$, $4$ by $4$, and $2$ by $2$, and indeed the full tableau of pairings is a square of $12=6+4+2$ by $12$. Within each square the diagonal is missing. Thus, the number of pairs within any such square-without-diagonal of sides $k$ must be $k\times k - k = k(k-1)$. Sum these values over the red socks ($k=6$), green socks ($k=4$), and blue socks ($k=2$), finally dividing by the total ($k=12$).
A general formula for any numbers of various kinds of socks follows immediately. | How to calculate the probability of matching sock from a drawer? [closed] | Here are all the different ways of pairing one sock with another different one, arranged systematically:
"Random" in this context means that each pairing is equally likely. Therefore, to find the pr | How to calculate the probability of matching sock from a drawer? [closed]
Here are all the different ways of pairing one sock with another different one, arranged systematically:
"Random" in this context means that each pairing is equally likely. Therefore, to find the probability of a color match, count the color-matched pairs and divide by the total.
Counting is made easier by noting that the color-matched socks occur within squares of $6$ by $6$, $4$ by $4$, and $2$ by $2$, and indeed the full tableau of pairings is a square of $12=6+4+2$ by $12$. Within each square the diagonal is missing. Thus, the number of pairs within any such square-without-diagonal of sides $k$ must be $k\times k - k = k(k-1)$. Sum these values over the red socks ($k=6$), green socks ($k=4$), and blue socks ($k=2$), finally dividing by the total ($k=12$).
A general formula for any numbers of various kinds of socks follows immediately. | How to calculate the probability of matching sock from a drawer? [closed]
Here are all the different ways of pairing one sock with another different one, arranged systematically:
"Random" in this context means that each pairing is equally likely. Therefore, to find the pr |
38,771 | How to calculate the probability of matching sock from a drawer? [closed] | Try starting here: What is the probability of drawing two red socks? Well, there are 6 red socks, and you need to choose two of them, meaning there are 6C2 (read "6 choose 2") ways to succeed, or 15 ways to draw two red socks. There are 12 total socks, and you choose 2, so there are 12C2 total combinations of 2 socks, or 66 total combinations of two. Since you have 66 possible combinations, and 15 of them are ways to succeed in drawing two red socks, the probability of drawing two reds is 15/66 or 22.7%. Hopefully you can take it from there. | How to calculate the probability of matching sock from a drawer? [closed] | Try starting here: What is the probability of drawing two red socks? Well, there are 6 red socks, and you need to choose two of them, meaning there are 6C2 (read "6 choose 2") ways to succeed, or 15 w | How to calculate the probability of matching sock from a drawer? [closed]
Try starting here: What is the probability of drawing two red socks? Well, there are 6 red socks, and you need to choose two of them, meaning there are 6C2 (read "6 choose 2") ways to succeed, or 15 ways to draw two red socks. There are 12 total socks, and you choose 2, so there are 12C2 total combinations of 2 socks, or 66 total combinations of two. Since you have 66 possible combinations, and 15 of them are ways to succeed in drawing two red socks, the probability of drawing two reds is 15/66 or 22.7%. Hopefully you can take it from there. | How to calculate the probability of matching sock from a drawer? [closed]
Try starting here: What is the probability of drawing two red socks? Well, there are 6 red socks, and you need to choose two of them, meaning there are 6C2 (read "6 choose 2") ways to succeed, or 15 w |
38,772 | How to calculate the probability of matching sock from a drawer? [closed] | Here's what I got, P2red, 30/132 P2green, 12/132, P2black, 2/132, sum of 3 probabilities = 44/132 = 1/3, so 33.33% chance of matching, 66.66% chance of looking like a scrub | How to calculate the probability of matching sock from a drawer? [closed] | Here's what I got, P2red, 30/132 P2green, 12/132, P2black, 2/132, sum of 3 probabilities = 44/132 = 1/3, so 33.33% chance of matching, 66.66% chance of looking like a scrub | How to calculate the probability of matching sock from a drawer? [closed]
Here's what I got, P2red, 30/132 P2green, 12/132, P2black, 2/132, sum of 3 probabilities = 44/132 = 1/3, so 33.33% chance of matching, 66.66% chance of looking like a scrub | How to calculate the probability of matching sock from a drawer? [closed]
Here's what I got, P2red, 30/132 P2green, 12/132, P2black, 2/132, sum of 3 probabilities = 44/132 = 1/3, so 33.33% chance of matching, 66.66% chance of looking like a scrub |
38,773 | Joint entropy of two random variables | Entropy (joint entropy included), is a property of the distribution that a random variable follows. The available sample (and hence the timing of observation) plays no role in it.
Copying for Cover & Thomas, the joint entropy $H(X,Y)$ of two discrete random variables $X, Y,$ with joint distribution $p(x,y)$, is defined as
$$H(X,Y) = - \sum_{S_X}\sum_{S_Y}p(x,y)\log p(x,y) $$
Examine the expression: the sums are taken over all possible values of $X$ and $Y$, i.e. over all the values that belong to the support of each r.v. ($S_X$ and $S_Y$ respectively), irrespective of whether some of these values may not materialize or be observed in a sample. What we actually observe, or when, plays no role, in calculating entropy, and joint entropy in particular.
Turning to your specific example: The side of a coin itself can not be modeled as a random variable. A random variable maps events into real numbers. The side of a coin is not an event. Observing one of the two sides is an event. Not observing a side, is an event. So let's define a random variable $X$ by "$X$ takes the value $1$ if heads is observed, $0$ otherwise". And define $Y$ by "$Y$ takes the value $1$ if tails is observed, $0$ otherwise". Assume the coin is fair. The joint distribution of these two random variables is then described by
$$\begin{align}
P(X=1,Y=1) &= 0 \\
P(X=1,Y=0) &= 0.5 \\
P(X=0,Y=1) &= 0.5 \\
P(X=0,Y=0) &= 0
\end{align}$$
Note that the numerical mapping we chose (the zero/one values) does not play, as numbers go, any decisive part in the probabilities assigned -we could have chosen a 5/6 mapping for $X$ and a 56/89 mapping for $Y$ (or whatever) -the allocation of probabilities in the joint distribution would have been the same (it is the underlying structure of events that is the critical factor).
Next, as always, we consider the distribution at non-zero values, so
$$H(X,Y) = - 0.5\log(0.5) - 0.5\log(0.5) $$
and using base-2 for the logarithm we get
$$H(X,Y) = - 0.5(-1) - 0.5(-1) = 1 $$
Finally, you can easily find that the entropy of $X$ (and likewise for $Y$) is
$$H(X) = - \sum_{S_X}p(x)\log p(x) = - 0.5(-1) - 0.5(-1) = 1 $$
So in this case $H(X,Y) = H(X) = H(Y)$. But the general expression for the decomposition of joint entropy is
$$H(X,Y) = H(X) + H(Y\mid X) = H(Y) + H(X\mid Y)$$
where $H(Y\mid X)$ and $H(X\mid Y)$ are conditional entropies. Then we conclude that $H(Y\mid X) = H(X\mid Y) = 0$ in this case. The intuition is straightforward: given $X$ what has happened to $Y$ is certain (and likewise in reverse), so conditional entropy is zero. | Joint entropy of two random variables | Entropy (joint entropy included), is a property of the distribution that a random variable follows. The available sample (and hence the timing of observation) plays no role in it.
Copying for Cover | Joint entropy of two random variables
Entropy (joint entropy included), is a property of the distribution that a random variable follows. The available sample (and hence the timing of observation) plays no role in it.
Copying for Cover & Thomas, the joint entropy $H(X,Y)$ of two discrete random variables $X, Y,$ with joint distribution $p(x,y)$, is defined as
$$H(X,Y) = - \sum_{S_X}\sum_{S_Y}p(x,y)\log p(x,y) $$
Examine the expression: the sums are taken over all possible values of $X$ and $Y$, i.e. over all the values that belong to the support of each r.v. ($S_X$ and $S_Y$ respectively), irrespective of whether some of these values may not materialize or be observed in a sample. What we actually observe, or when, plays no role, in calculating entropy, and joint entropy in particular.
Turning to your specific example: The side of a coin itself can not be modeled as a random variable. A random variable maps events into real numbers. The side of a coin is not an event. Observing one of the two sides is an event. Not observing a side, is an event. So let's define a random variable $X$ by "$X$ takes the value $1$ if heads is observed, $0$ otherwise". And define $Y$ by "$Y$ takes the value $1$ if tails is observed, $0$ otherwise". Assume the coin is fair. The joint distribution of these two random variables is then described by
$$\begin{align}
P(X=1,Y=1) &= 0 \\
P(X=1,Y=0) &= 0.5 \\
P(X=0,Y=1) &= 0.5 \\
P(X=0,Y=0) &= 0
\end{align}$$
Note that the numerical mapping we chose (the zero/one values) does not play, as numbers go, any decisive part in the probabilities assigned -we could have chosen a 5/6 mapping for $X$ and a 56/89 mapping for $Y$ (or whatever) -the allocation of probabilities in the joint distribution would have been the same (it is the underlying structure of events that is the critical factor).
Next, as always, we consider the distribution at non-zero values, so
$$H(X,Y) = - 0.5\log(0.5) - 0.5\log(0.5) $$
and using base-2 for the logarithm we get
$$H(X,Y) = - 0.5(-1) - 0.5(-1) = 1 $$
Finally, you can easily find that the entropy of $X$ (and likewise for $Y$) is
$$H(X) = - \sum_{S_X}p(x)\log p(x) = - 0.5(-1) - 0.5(-1) = 1 $$
So in this case $H(X,Y) = H(X) = H(Y)$. But the general expression for the decomposition of joint entropy is
$$H(X,Y) = H(X) + H(Y\mid X) = H(Y) + H(X\mid Y)$$
where $H(Y\mid X)$ and $H(X\mid Y)$ are conditional entropies. Then we conclude that $H(Y\mid X) = H(X\mid Y) = 0$ in this case. The intuition is straightforward: given $X$ what has happened to $Y$ is certain (and likewise in reverse), so conditional entropy is zero. | Joint entropy of two random variables
Entropy (joint entropy included), is a property of the distribution that a random variable follows. The available sample (and hence the timing of observation) plays no role in it.
Copying for Cover |
38,774 | Correct estimation of arguments for glmmLasso function | the glmmLasso package contains a demo file, where several strategies are shown, how the optimal tuning parameter lambda. I suggest to start with a high values for lambda, such that all covariates are set to zero and then reduce it step by step. It increase speed, if the final coefficient estimates corresponding to a lambda are used as starting values for the next smaller lambda.
The argument start of the control list is a vector of starting values for all model parameters, i.e. all fixed effects (usually including the intercept) followed by all random effects (and thus depending on the length of your gouping factor and on the structure of your random terms), see the documentation of glmmLassoControl. For example, if you fit the following GLMM with a simple random intercept:
fit <- glmmLasso(y ~ x1 + ... + x10, rnd = list(id=~1), data = ..., ... )
and suppose your grouping factor id contains 80 individuals, then the start vector would have to be of length 1(intercept)+10(fixed effects)+80(random effects)=91.
In my experience, the model corresponding to the lambda with the lowest BIC is usually quite sparse. So what I would suggest is to check first, if really all covariates have been standardized in adavnace to have variance one. Furthermore, have a look on the coefficient paths for your sequence of lambda values to check if they build up as one would typically expect for LASSO. | Correct estimation of arguments for glmmLasso function | the glmmLasso package contains a demo file, where several strategies are shown, how the optimal tuning parameter lambda. I suggest to start with a high values for lambda, such that all covariates are | Correct estimation of arguments for glmmLasso function
the glmmLasso package contains a demo file, where several strategies are shown, how the optimal tuning parameter lambda. I suggest to start with a high values for lambda, such that all covariates are set to zero and then reduce it step by step. It increase speed, if the final coefficient estimates corresponding to a lambda are used as starting values for the next smaller lambda.
The argument start of the control list is a vector of starting values for all model parameters, i.e. all fixed effects (usually including the intercept) followed by all random effects (and thus depending on the length of your gouping factor and on the structure of your random terms), see the documentation of glmmLassoControl. For example, if you fit the following GLMM with a simple random intercept:
fit <- glmmLasso(y ~ x1 + ... + x10, rnd = list(id=~1), data = ..., ... )
and suppose your grouping factor id contains 80 individuals, then the start vector would have to be of length 1(intercept)+10(fixed effects)+80(random effects)=91.
In my experience, the model corresponding to the lambda with the lowest BIC is usually quite sparse. So what I would suggest is to check first, if really all covariates have been standardized in adavnace to have variance one. Furthermore, have a look on the coefficient paths for your sequence of lambda values to check if they build up as one would typically expect for LASSO. | Correct estimation of arguments for glmmLasso function
the glmmLasso package contains a demo file, where several strategies are shown, how the optimal tuning parameter lambda. I suggest to start with a high values for lambda, such that all covariates are |
38,775 | How is the Weighted Gini Criterion defined? | The implementation available at Breiman's website uses the weighted random forest method described in the paper. It's in Fortran 77 though, which may be off-putting to you. I also found the method that they use to calculate the impurity to be more unclear and complicated than needs be, but that's just my opinion (and probably an artifact of the method that they use to grow their trees).
For any potential split, the weight of all the observations in a potential child node, $c$, is
$$t_c = \sum_i w_i * n_i$$
where $n_i$ is the number of observations of class $i$ in $c$, and $w_i$ is the weight assigned to class $i$. The impurity of child node $c$ is then
$$i_c = 1 - \sum_i (w_i * n_i / t_c)^2$$
where $n_i$ is again the number of observations of class $i$ in the node, $w_i$ is the weight assigned to the class and $t_c$ is as calculated previously.
The impurity of the entire potential split is then
$$\sum_c(t_c / t_p) * i_c$$
where $t_c$ and $i_c$ are as calculated previously, and $t_p$ is the total weight of all observations in the parent node that is being split. Basically the fraction of the parent node's total weight that is in each child node $c$ multiplied by $c$'s impurity. You then choose the potential split that has the lowest impurity over all potential splits. | How is the Weighted Gini Criterion defined? | The implementation available at Breiman's website uses the weighted random forest method described in the paper. It's in Fortran 77 though, which may be off-putting to you. I also found the method th | How is the Weighted Gini Criterion defined?
The implementation available at Breiman's website uses the weighted random forest method described in the paper. It's in Fortran 77 though, which may be off-putting to you. I also found the method that they use to calculate the impurity to be more unclear and complicated than needs be, but that's just my opinion (and probably an artifact of the method that they use to grow their trees).
For any potential split, the weight of all the observations in a potential child node, $c$, is
$$t_c = \sum_i w_i * n_i$$
where $n_i$ is the number of observations of class $i$ in $c$, and $w_i$ is the weight assigned to class $i$. The impurity of child node $c$ is then
$$i_c = 1 - \sum_i (w_i * n_i / t_c)^2$$
where $n_i$ is again the number of observations of class $i$ in the node, $w_i$ is the weight assigned to the class and $t_c$ is as calculated previously.
The impurity of the entire potential split is then
$$\sum_c(t_c / t_p) * i_c$$
where $t_c$ and $i_c$ are as calculated previously, and $t_p$ is the total weight of all observations in the parent node that is being split. Basically the fraction of the parent node's total weight that is in each child node $c$ multiplied by $c$'s impurity. You then choose the potential split that has the lowest impurity over all potential splits. | How is the Weighted Gini Criterion defined?
The implementation available at Breiman's website uses the weighted random forest method described in the paper. It's in Fortran 77 though, which may be off-putting to you. I also found the method th |
38,776 | How is the Weighted Gini Criterion defined? | Just a follow-up on Simon's answer.
The Gini index (impurity index) for a node $c$ can be defined as:
$$ i_c = \sum_i f_i \cdot ( 1- f_i) = 1 - \sum_i f_i^2$$
where $f_i$ is the fraction of records which belong to class $i$.
If we have a two class problem we can plot the Gini index varying the relative number of records of the first class $f$. That is $f_1 = f$ and $f_2 = f - f_1$.
We have very high impurity when the class distribution is uniform.
If we assign a weight to each class we are actually rebalancing the impurity index - a high weight for one class (say $\bar{i}$) leads to a stronger decrease of impurity when the number of records for that class increases. We will not have the maximum impurity when the class distribution is uniform anymore. Just a small amount of records in $\bar{i}$ will be enough to decrease the node impurity.
We can still sketch a two class problem example. In Simon's formulas our $f_i$s are
$$f_i = \frac{w_i \cdot n_i}{\sum_i w_i \cdot n_i}$$
We can see that the formula does not change if $\sum_i n_i = 1$ and $\sum_i w_i = 1$ (it is enough to multiply numerator and denominator by the total number of records and total weight). Let $f$ be
$$f = \frac{w \cdot n}{w \cdot n + (1-w)(1-n)}$$
where $n$ is the relative number of records for the first class and $w$ their weight. Now we could compute the Gini when we vary the relative number of records for the first class $n$.
For example if we choose a weight of $0.9$ we have maximum impurity when $n \approx 0.1$. If $n$ increases the impurity steeply decreases as well.
If we define the weigthed Gini index as the OP did we would for example have a strange behaviour in a two class problem:
$$\sum_i w_i \cdot f_i \cdot (1 - f_i) = w \cdot f \cdot (1 - f) + (1 - w) \cdot (1-f) \cdot f = f \cdot ( 1- f)$$
However, I found a paper that uses that index here but I didn't read it, so I might be wrong.
Breiman's weighted index makes actually sense - we are trying to reweight the classes in a cost-sensitive way. The same approach is used in the MetaCost classifier implemented in WEKA.
In case anyone is interested, this is the R code I used to plot the figures:
require(ggplot2)
# two class probability distribution
f <- seq(0,1,0.01)
# Standard Gini impurity
# f1 = f and f2 = 1 - f
Gini <- f*(1-f) + (1-f)*f
qplot(f,Gini, geom = "path")
# Weighted Gini impurity
w <- seq(0,1,0.1)
w_ <- as.vector( sapply(w, function(x) rep(x,length(f))))
n <- rep(f,length(w))
f <- w_*n / ( w_*n + (1-w_)*(1-n) )
WeightedGini <- f*(1-f) + (1-f)*f
Weight <- as.factor(w_)
qplot(n, WeightedGini, colour = Weight, geom = "path") | How is the Weighted Gini Criterion defined? | Just a follow-up on Simon's answer.
The Gini index (impurity index) for a node $c$ can be defined as:
$$ i_c = \sum_i f_i \cdot ( 1- f_i) = 1 - \sum_i f_i^2$$
where $f_i$ is the fraction of records w | How is the Weighted Gini Criterion defined?
Just a follow-up on Simon's answer.
The Gini index (impurity index) for a node $c$ can be defined as:
$$ i_c = \sum_i f_i \cdot ( 1- f_i) = 1 - \sum_i f_i^2$$
where $f_i$ is the fraction of records which belong to class $i$.
If we have a two class problem we can plot the Gini index varying the relative number of records of the first class $f$. That is $f_1 = f$ and $f_2 = f - f_1$.
We have very high impurity when the class distribution is uniform.
If we assign a weight to each class we are actually rebalancing the impurity index - a high weight for one class (say $\bar{i}$) leads to a stronger decrease of impurity when the number of records for that class increases. We will not have the maximum impurity when the class distribution is uniform anymore. Just a small amount of records in $\bar{i}$ will be enough to decrease the node impurity.
We can still sketch a two class problem example. In Simon's formulas our $f_i$s are
$$f_i = \frac{w_i \cdot n_i}{\sum_i w_i \cdot n_i}$$
We can see that the formula does not change if $\sum_i n_i = 1$ and $\sum_i w_i = 1$ (it is enough to multiply numerator and denominator by the total number of records and total weight). Let $f$ be
$$f = \frac{w \cdot n}{w \cdot n + (1-w)(1-n)}$$
where $n$ is the relative number of records for the first class and $w$ their weight. Now we could compute the Gini when we vary the relative number of records for the first class $n$.
For example if we choose a weight of $0.9$ we have maximum impurity when $n \approx 0.1$. If $n$ increases the impurity steeply decreases as well.
If we define the weigthed Gini index as the OP did we would for example have a strange behaviour in a two class problem:
$$\sum_i w_i \cdot f_i \cdot (1 - f_i) = w \cdot f \cdot (1 - f) + (1 - w) \cdot (1-f) \cdot f = f \cdot ( 1- f)$$
However, I found a paper that uses that index here but I didn't read it, so I might be wrong.
Breiman's weighted index makes actually sense - we are trying to reweight the classes in a cost-sensitive way. The same approach is used in the MetaCost classifier implemented in WEKA.
In case anyone is interested, this is the R code I used to plot the figures:
require(ggplot2)
# two class probability distribution
f <- seq(0,1,0.01)
# Standard Gini impurity
# f1 = f and f2 = 1 - f
Gini <- f*(1-f) + (1-f)*f
qplot(f,Gini, geom = "path")
# Weighted Gini impurity
w <- seq(0,1,0.1)
w_ <- as.vector( sapply(w, function(x) rep(x,length(f))))
n <- rep(f,length(w))
f <- w_*n / ( w_*n + (1-w_)*(1-n) )
WeightedGini <- f*(1-f) + (1-f)*f
Weight <- as.factor(w_)
qplot(n, WeightedGini, colour = Weight, geom = "path") | How is the Weighted Gini Criterion defined?
Just a follow-up on Simon's answer.
The Gini index (impurity index) for a node $c$ can be defined as:
$$ i_c = \sum_i f_i \cdot ( 1- f_i) = 1 - \sum_i f_i^2$$
where $f_i$ is the fraction of records w |
38,777 | Dummy variables in multiple regression, why use an intercept? | Things like the predictions, residuals, full-reduced model tests, etc. will not be affected by the change that you propose, but what does change is the interpretation and tests on the individual terms.
Most regression routines will provide an automatic test of whether a term is 0 or not. This is meaningful when a term represents the difference between two group means (what we get when we include an intercept), but is testing whether each of the group means equals 0 meaningful? The same goes for the confidence intervals and we usually want to know if groups differ from each other. If every term just represents a mean then we compute confidence intervals for the means, then people try to interpret the amount of a difference by seeing if the intervals overlap, but this is very inferior to looking at a confidence interval on a difference. | Dummy variables in multiple regression, why use an intercept? | Things like the predictions, residuals, full-reduced model tests, etc. will not be affected by the change that you propose, but what does change is the interpretation and tests on the individual terms | Dummy variables in multiple regression, why use an intercept?
Things like the predictions, residuals, full-reduced model tests, etc. will not be affected by the change that you propose, but what does change is the interpretation and tests on the individual terms.
Most regression routines will provide an automatic test of whether a term is 0 or not. This is meaningful when a term represents the difference between two group means (what we get when we include an intercept), but is testing whether each of the group means equals 0 meaningful? The same goes for the confidence intervals and we usually want to know if groups differ from each other. If every term just represents a mean then we compute confidence intervals for the means, then people try to interpret the amount of a difference by seeing if the intervals overlap, but this is very inferior to looking at a confidence interval on a difference. | Dummy variables in multiple regression, why use an intercept?
Things like the predictions, residuals, full-reduced model tests, etc. will not be affected by the change that you propose, but what does change is the interpretation and tests on the individual terms |
38,778 | Dummy variables in multiple regression, why use an intercept? | @GregSnow is right that this change doesn't really matter. Let me add a few details to extend that. What you are talking about is sometimes called level means coding, whereas the default coding scheme is called reference level coding. Note that there are many possible valid coding schemes. If you have a categorical variable with only two levels, then the t-test of the beta that comes by default in the regression output with any statistical software is more meaningful when you had used reference level coding.
On the other hand, when you have a categorical variable with multiple categories, which coding scheme you use is just a matter of taste. To get a predicted value, you will have to solve the regression equation for $\hat y$ at the relevant spot in the covariate space either way. To test if the categorical variable is related to the response, you will need to use an F change test (discussed here) either way, etc.
To address your specific questions more concretely: if you use level means coding instead of reference level coding, the F-statistic will be the same; the t-statistics will change in that they will now test whether your level means are zero, as @GregSnow explains; and the inclusion of continuous covariates will be the same. | Dummy variables in multiple regression, why use an intercept? | @GregSnow is right that this change doesn't really matter. Let me add a few details to extend that. What you are talking about is sometimes called level means coding, whereas the default coding sche | Dummy variables in multiple regression, why use an intercept?
@GregSnow is right that this change doesn't really matter. Let me add a few details to extend that. What you are talking about is sometimes called level means coding, whereas the default coding scheme is called reference level coding. Note that there are many possible valid coding schemes. If you have a categorical variable with only two levels, then the t-test of the beta that comes by default in the regression output with any statistical software is more meaningful when you had used reference level coding.
On the other hand, when you have a categorical variable with multiple categories, which coding scheme you use is just a matter of taste. To get a predicted value, you will have to solve the regression equation for $\hat y$ at the relevant spot in the covariate space either way. To test if the categorical variable is related to the response, you will need to use an F change test (discussed here) either way, etc.
To address your specific questions more concretely: if you use level means coding instead of reference level coding, the F-statistic will be the same; the t-statistics will change in that they will now test whether your level means are zero, as @GregSnow explains; and the inclusion of continuous covariates will be the same. | Dummy variables in multiple regression, why use an intercept?
@GregSnow is right that this change doesn't really matter. Let me add a few details to extend that. What you are talking about is sometimes called level means coding, whereas the default coding sche |
38,779 | Why is the Likelihood function NOT a case of the inverse fallacy? | From your link:
Confusion of the inverse, also called the conditional probability fallacy or the inverse fallacy, is a logical fallacy whereupon a conditional probability is equivocated with its inverse
i.e. this is talking about making the mistake of thinking P(A|B) is the same as P(B|A).
The likelihood is, however, not regarded as a conditional probability in that sense at all. In other words, $L(\theta|\text{data})$ is clearly understood NOT to be $P(\theta|\text{data})$.
(Indeed, as a function of $\theta$, generally it doesn't even integrate to 1! It can't be a probability distribution in that sense.)
When discussing likelihood in probability terms, people always talk about $P(\text{data}|\theta)$ ... that is, the thing it's defined in terms of.
Given the likelihood $L(\theta|\text{data})$ is not taken to be a conditional probability $P(\theta|\text{data})$, in what sense is this the 'inverse fallacy'? | Why is the Likelihood function NOT a case of the inverse fallacy? | From your link:
Confusion of the inverse, also called the conditional probability fallacy or the inverse fallacy, is a logical fallacy whereupon a conditional probability is equivocated with its inve | Why is the Likelihood function NOT a case of the inverse fallacy?
From your link:
Confusion of the inverse, also called the conditional probability fallacy or the inverse fallacy, is a logical fallacy whereupon a conditional probability is equivocated with its inverse
i.e. this is talking about making the mistake of thinking P(A|B) is the same as P(B|A).
The likelihood is, however, not regarded as a conditional probability in that sense at all. In other words, $L(\theta|\text{data})$ is clearly understood NOT to be $P(\theta|\text{data})$.
(Indeed, as a function of $\theta$, generally it doesn't even integrate to 1! It can't be a probability distribution in that sense.)
When discussing likelihood in probability terms, people always talk about $P(\text{data}|\theta)$ ... that is, the thing it's defined in terms of.
Given the likelihood $L(\theta|\text{data})$ is not taken to be a conditional probability $P(\theta|\text{data})$, in what sense is this the 'inverse fallacy'? | Why is the Likelihood function NOT a case of the inverse fallacy?
From your link:
Confusion of the inverse, also called the conditional probability fallacy or the inverse fallacy, is a logical fallacy whereupon a conditional probability is equivocated with its inve |
38,780 | Why is the Likelihood function NOT a case of the inverse fallacy? | It's not saying $P(\theta|\text{data})$ = $P (\text{data}|\theta)$. It's defining the likelihood function. | Why is the Likelihood function NOT a case of the inverse fallacy? | It's not saying $P(\theta|\text{data})$ = $P (\text{data}|\theta)$. It's defining the likelihood function. | Why is the Likelihood function NOT a case of the inverse fallacy?
It's not saying $P(\theta|\text{data})$ = $P (\text{data}|\theta)$. It's defining the likelihood function. | Why is the Likelihood function NOT a case of the inverse fallacy?
It's not saying $P(\theta|\text{data})$ = $P (\text{data}|\theta)$. It's defining the likelihood function. |
38,781 | How to define initial probabilities for HMM? | 1. How to decide number of Hidden States (although HMM says we don't need to know, we just have to make a guess, even for making guess what should be the best criteria)
The number of hidden states is problem dependent. For example in speech recognition and synthesis, 3 and 5 states are commonly used. The reason for using these is that speech is a highly variable data. So the distribution at different instants of speech sounds (phonemes) varies with time and each state models the different distributions.
2. Once define hidden states let say 5, then how to define initial probabilities for each hidden state and the transitional probabilities among each other...
An HMM can be defined by (A, B, $\pi$), where A is a matrix of state transition probabilities, B is a vector of state emission probabilities and $\pi$ (a special member of A) is a vector of initial state distributions. The following steps are taken to estimate these parameters:
For the A and $\pi$ parameters, randomly initialise the HMM (between 0 and 1)
Initialise the B parameter by uniformly segmenting the training data and estimating the global mean and variance. The B parameter deals with the mean and variances of each state
Re-estimate and refine the parameters using the Baum-Welch algorithm. This is a variant of the well-known Expectation-Maximation (EM) algorithm.
References:
Rabiner, L. 1989. A tutorial on hidden Markov models and selected applications in speech recognition.
Baum, L.E., T. Petrie, G. Soules and N. Weiss. 1970. A Maximization Technique Occurring in the Statistical Analysis of Probabilistic Functions of Markov Chains. The Annals of Mathematical Statistics Vol. 41, No. 1, pp. 164-171.
Dempster, A. P., N. M. Laird, and D. B. Rubin. 1977. Maximum likeli- hood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society. Series B (Methodological) 39 (1), pp. 1-38. | How to define initial probabilities for HMM? | 1. How to decide number of Hidden States (although HMM says we don't need to know, we just have to make a guess, even for making guess what should be the best criteria)
The number of hidden states is | How to define initial probabilities for HMM?
1. How to decide number of Hidden States (although HMM says we don't need to know, we just have to make a guess, even for making guess what should be the best criteria)
The number of hidden states is problem dependent. For example in speech recognition and synthesis, 3 and 5 states are commonly used. The reason for using these is that speech is a highly variable data. So the distribution at different instants of speech sounds (phonemes) varies with time and each state models the different distributions.
2. Once define hidden states let say 5, then how to define initial probabilities for each hidden state and the transitional probabilities among each other...
An HMM can be defined by (A, B, $\pi$), where A is a matrix of state transition probabilities, B is a vector of state emission probabilities and $\pi$ (a special member of A) is a vector of initial state distributions. The following steps are taken to estimate these parameters:
For the A and $\pi$ parameters, randomly initialise the HMM (between 0 and 1)
Initialise the B parameter by uniformly segmenting the training data and estimating the global mean and variance. The B parameter deals with the mean and variances of each state
Re-estimate and refine the parameters using the Baum-Welch algorithm. This is a variant of the well-known Expectation-Maximation (EM) algorithm.
References:
Rabiner, L. 1989. A tutorial on hidden Markov models and selected applications in speech recognition.
Baum, L.E., T. Petrie, G. Soules and N. Weiss. 1970. A Maximization Technique Occurring in the Statistical Analysis of Probabilistic Functions of Markov Chains. The Annals of Mathematical Statistics Vol. 41, No. 1, pp. 164-171.
Dempster, A. P., N. M. Laird, and D. B. Rubin. 1977. Maximum likeli- hood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society. Series B (Methodological) 39 (1), pp. 1-38. | How to define initial probabilities for HMM?
1. How to decide number of Hidden States (although HMM says we don't need to know, we just have to make a guess, even for making guess what should be the best criteria)
The number of hidden states is |
38,782 | How to define initial probabilities for HMM? | The usual, uninspiring and uninformative answer to this question is that 'the dynamics of your system / the nature of the physical problem will indicate how many hidden states there are', which translates into: "Take a pick and get over it". However, I do not buy into this. I think most problems are more complex than that, hence your question is a very valid one.
Let us assume you are using a Gaussian distribution to model your emission (observation) variables. When fitting an HMM, what you are doing is essentially temporal clustering. Hence, you could utilise a quick and simpler clustering method to form the initial guesstimates of your Gaussian distributions per state. This is also mentioned in Rabiner's paper - the main reference for HMM's.
1) You can run a (simple) k-means on your dataset to roughly estimate the optimal number of clusters and the locations of the centroids (mean vector) in your dataset. Have a look at here for a great coverage on the topic of how to determine the number of clusters.
2) Better yet, you can choose to fit a mixture of Gaussians (or any mixture model) on your dataset to see how many mixture components best explain your dataset and what the sufficient statistics (Mean vector, Covariances) are. You can use these outputs to form your initial parameters while training the HMM - which is computationally harder than training a Mixture model (and obviously a k-means routine) primarily due to the serial dependencies that go into the loglikelihood (and therefore Expectation-Maximisation) calculation.
Now, the important thing here is that these clustering techniques will not take into account the serial dependencies (as a HMM does via its transition matrix) while calculating what point most likely belongs to what state. Nevertheless they will give you rough estimations as to what your starting points (e.g. Mean vector, Covariance vector, prior distributions) should be.
You can, for instance, calculate the loglikelihood of your HMM trained in this way and then compare it to the loglikelihood of one that has been trained using randomised initial values to observe the difference yourself.
This is in a way analogous to, for instance, starting-off the global optimisation for a non-convex problem with the optimal values to its simplified (approximate) convex version. You do steps 1 and/or 2 to reduce the search space. Needless to say, the final values you find are not in anyway guaranteed to be the global solution to your optimisation problem - but maybe sufficiently good for your purposes. | How to define initial probabilities for HMM? | The usual, uninspiring and uninformative answer to this question is that 'the dynamics of your system / the nature of the physical problem will indicate how many hidden states there are', which trans | How to define initial probabilities for HMM?
The usual, uninspiring and uninformative answer to this question is that 'the dynamics of your system / the nature of the physical problem will indicate how many hidden states there are', which translates into: "Take a pick and get over it". However, I do not buy into this. I think most problems are more complex than that, hence your question is a very valid one.
Let us assume you are using a Gaussian distribution to model your emission (observation) variables. When fitting an HMM, what you are doing is essentially temporal clustering. Hence, you could utilise a quick and simpler clustering method to form the initial guesstimates of your Gaussian distributions per state. This is also mentioned in Rabiner's paper - the main reference for HMM's.
1) You can run a (simple) k-means on your dataset to roughly estimate the optimal number of clusters and the locations of the centroids (mean vector) in your dataset. Have a look at here for a great coverage on the topic of how to determine the number of clusters.
2) Better yet, you can choose to fit a mixture of Gaussians (or any mixture model) on your dataset to see how many mixture components best explain your dataset and what the sufficient statistics (Mean vector, Covariances) are. You can use these outputs to form your initial parameters while training the HMM - which is computationally harder than training a Mixture model (and obviously a k-means routine) primarily due to the serial dependencies that go into the loglikelihood (and therefore Expectation-Maximisation) calculation.
Now, the important thing here is that these clustering techniques will not take into account the serial dependencies (as a HMM does via its transition matrix) while calculating what point most likely belongs to what state. Nevertheless they will give you rough estimations as to what your starting points (e.g. Mean vector, Covariance vector, prior distributions) should be.
You can, for instance, calculate the loglikelihood of your HMM trained in this way and then compare it to the loglikelihood of one that has been trained using randomised initial values to observe the difference yourself.
This is in a way analogous to, for instance, starting-off the global optimisation for a non-convex problem with the optimal values to its simplified (approximate) convex version. You do steps 1 and/or 2 to reduce the search space. Needless to say, the final values you find are not in anyway guaranteed to be the global solution to your optimisation problem - but maybe sufficiently good for your purposes. | How to define initial probabilities for HMM?
The usual, uninspiring and uninformative answer to this question is that 'the dynamics of your system / the nature of the physical problem will indicate how many hidden states there are', which trans |
38,783 | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire population? | I think you have two different viewpoints and no correct or incorrect answer. But I would be more inclined to go with 2. Although in 1 you said you have included every seminar held to date it seems that your universe includes future seminars as well.
But accepting 2 does not settle the issue between R square and adjusted R square. The reason adjusted R square is included in the first place is that if the size of the model parameters or covariates is large relative to the size of the sample the ordinary R square will tend to overestimate the amount of variation that the model explains. It is the percentage of variance explained by the model for the observed data set but it overestimates the amount of variation the model will explain on a new data set randomly sampled from the population. The adjusted R square makes an effort to account for this bias. But if the sample size is very large relative to the number of covariates R square and adjusted R square won't differ much and choosing adjusted R square is far less important than if the sample size was only slightly larger than the number of parameters estimated in the model.
So I see the choice of adjusted R square over R square being more a matter of the relative size of the sample size to the number of parameters rather than whether or not the sample represent the enitre population or just a random piece of it. | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire | I think you have two different viewpoints and no correct or incorrect answer. But I would be more inclined to go with 2. Although in 1 you said you have included every seminar held to date it seems | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire population?
I think you have two different viewpoints and no correct or incorrect answer. But I would be more inclined to go with 2. Although in 1 you said you have included every seminar held to date it seems that your universe includes future seminars as well.
But accepting 2 does not settle the issue between R square and adjusted R square. The reason adjusted R square is included in the first place is that if the size of the model parameters or covariates is large relative to the size of the sample the ordinary R square will tend to overestimate the amount of variation that the model explains. It is the percentage of variance explained by the model for the observed data set but it overestimates the amount of variation the model will explain on a new data set randomly sampled from the population. The adjusted R square makes an effort to account for this bias. But if the sample size is very large relative to the number of covariates R square and adjusted R square won't differ much and choosing adjusted R square is far less important than if the sample size was only slightly larger than the number of parameters estimated in the model.
So I see the choice of adjusted R square over R square being more a matter of the relative size of the sample size to the number of parameters rather than whether or not the sample represent the enitre population or just a random piece of it. | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire
I think you have two different viewpoints and no correct or incorrect answer. But I would be more inclined to go with 2. Although in 1 you said you have included every seminar held to date it seems |
38,784 | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire population? | It is not the case that one uses R-squared for entire populations and adjusted R-squared for samples. They each give different information. R-squared is the proportion of variability in the data accounted for by your model. Adjusted R-squared takes into account (i.e., adjusts for) the number of explanatory terms in your model. R-squared can never be decreased by adding additional terms because you can't explain less variation with more predictors. On the other hand, the adjusted R-squared, will increase only if the added predictors benefit the model. Conceptually, you can think of adjusted R-squared as penalizing complexity. Only if that added complexity significantly increases (i.e., more than would be expected by chance) the predictive power of the model will adjusted R-squared increase. Adding poor predictors can actually decrease adjusted R-squared. The real question then, is what are you trying to answer using this information? | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire | It is not the case that one uses R-squared for entire populations and adjusted R-squared for samples. They each give different information. R-squared is the proportion of variability in the data accou | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire population?
It is not the case that one uses R-squared for entire populations and adjusted R-squared for samples. They each give different information. R-squared is the proportion of variability in the data accounted for by your model. Adjusted R-squared takes into account (i.e., adjusts for) the number of explanatory terms in your model. R-squared can never be decreased by adding additional terms because you can't explain less variation with more predictors. On the other hand, the adjusted R-squared, will increase only if the added predictors benefit the model. Conceptually, you can think of adjusted R-squared as penalizing complexity. Only if that added complexity significantly increases (i.e., more than would be expected by chance) the predictive power of the model will adjusted R-squared increase. Adding poor predictors can actually decrease adjusted R-squared. The real question then, is what are you trying to answer using this information? | Whether to use r-square or adjusted r-square with a small sample size that may represent the entire
It is not the case that one uses R-squared for entire populations and adjusted R-squared for samples. They each give different information. R-squared is the proportion of variability in the data accou |
38,785 | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The boxplot and histogram tell you all by themselves that your data are skewed, especially in group A. The Shapiro-Wilk test is kind of pointless. With data thusly skewed the ANOVA isn't really appropriate. The Kruskal-Wallis rank sum test is based on the ranks, not the absolute values and doesn't require normality, either in the measures or residuals. It is the more appropriate test.
A quick Google search will tell you one requires normality and one does not.
One thing you might consider is that durations are an arbitrary representation of time. For example, you can indicate the duration of an event as 2 s or you can say the event has a rate 0.5 events/s. It's the exact same thing and both numbers can arbitrarily be interchanged for representation. However, rates tend to be much less skewed and more appropriate for statistical analysis. It's possible your rates are normally distributed and you can use ANOVA in that case.
If you do decide to look at rates, keep in mind that the direction of magnitude changes, a higher duration values = a lower rate value. Some people use a negative rate just to avoid that confusion. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The boxplot and histogram tell you all by themselves that your data are skewed, especially in group A. The Shapiro-Wilk test is kind of pointless. With data thusly skewed the ANOVA isn't really appr | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The boxplot and histogram tell you all by themselves that your data are skewed, especially in group A. The Shapiro-Wilk test is kind of pointless. With data thusly skewed the ANOVA isn't really appropriate. The Kruskal-Wallis rank sum test is based on the ranks, not the absolute values and doesn't require normality, either in the measures or residuals. It is the more appropriate test.
A quick Google search will tell you one requires normality and one does not.
One thing you might consider is that durations are an arbitrary representation of time. For example, you can indicate the duration of an event as 2 s or you can say the event has a rate 0.5 events/s. It's the exact same thing and both numbers can arbitrarily be interchanged for representation. However, rates tend to be much less skewed and more appropriate for statistical analysis. It's possible your rates are normally distributed and you can use ANOVA in that case.
If you do decide to look at rates, keep in mind that the direction of magnitude changes, a higher duration values = a lower rate value. Some people use a negative rate just to avoid that confusion. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The boxplot and histogram tell you all by themselves that your data are skewed, especially in group A. The Shapiro-Wilk test is kind of pointless. With data thusly skewed the ANOVA isn't really appr |
38,786 | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The Kruskal-Wallis test and the Anova test are testing different hypotheses, both could be correct, the answers differ because they are answering different questions. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The Kruskal-Wallis test and the Anova test are testing different hypotheses, both could be correct, the answers differ because they are answering different questions. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The Kruskal-Wallis test and the Anova test are testing different hypotheses, both could be correct, the answers differ because they are answering different questions. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The Kruskal-Wallis test and the Anova test are testing different hypotheses, both could be correct, the answers differ because they are answering different questions. |
38,787 | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | Two things to keep in mind: first, ANOVA is robust in the face of non-normality if sample sizes are equal - the larger the difference in sample sizes, the less reliable it is; second, the K-W test is not a test of means or medians - it is really a test of similarity of distributions and, if the distributions are similar, it can be interpreted as a test of location. In my experience, most people ignore that both the Mann-Whitney and K-W test expect (require) the groups being compared to have similar distributions.
Several options are available for your problem. You might try a data transformation (e.g., log) to put the data on a scale that yields normal distributions in each group. Or, you might try running standard ANOVA after replacing the data with their ranks. Both approaches are effective when the assumptions for ANOVA are violated. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | Two things to keep in mind: first, ANOVA is robust in the face of non-normality if sample sizes are equal - the larger the difference in sample sizes, the less reliable it is; second, the K-W test is | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
Two things to keep in mind: first, ANOVA is robust in the face of non-normality if sample sizes are equal - the larger the difference in sample sizes, the less reliable it is; second, the K-W test is not a test of means or medians - it is really a test of similarity of distributions and, if the distributions are similar, it can be interpreted as a test of location. In my experience, most people ignore that both the Mann-Whitney and K-W test expect (require) the groups being compared to have similar distributions.
Several options are available for your problem. You might try a data transformation (e.g., log) to put the data on a scale that yields normal distributions in each group. Or, you might try running standard ANOVA after replacing the data with their ranks. Both approaches are effective when the assumptions for ANOVA are violated. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
Two things to keep in mind: first, ANOVA is robust in the face of non-normality if sample sizes are equal - the larger the difference in sample sizes, the less reliable it is; second, the K-W test is |
38,788 | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The distributions all overlap very much. The Kruskal Wallis test seems to be indicating that the centers of the distributions are nearly the same. The distribution for group is highly skewed due to several very extremely high values. That is what causes the distribution to fail the Shapiro-Wilk test. The anova F test wrongly interprets group A to have a significantly larger mean because it "ignores" the skewness. The Kruskal Wallis test is giving the appropriate answer while the F test is not. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right? | The distributions all overlap very much. The Kruskal Wallis test seems to be indicating that the centers of the distributions are nearly the same. The distribution for group is highly skewed due to | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The distributions all overlap very much. The Kruskal Wallis test seems to be indicating that the centers of the distributions are nearly the same. The distribution for group is highly skewed due to several very extremely high values. That is what causes the distribution to fail the Shapiro-Wilk test. The anova F test wrongly interprets group A to have a significantly larger mean because it "ignores" the skewness. The Kruskal Wallis test is giving the appropriate answer while the F test is not. | Contradicting p-values for Anova and Kruskal-Wallis on same data: Which is right?
The distributions all overlap very much. The Kruskal Wallis test seems to be indicating that the centers of the distributions are nearly the same. The distribution for group is highly skewed due to |
38,789 | Why do AIC and BIC show inversed outputs? | AIC and BIC both penalize models for complexity, but they impose different penalties.
AIC = $2k - 2 \log(L)$ where $k$ is number of parameters and $L$ is likelihood.
BIC = $k*\log(n) - 2\log(L)$ where $n$ is number of subjects.
So, if $\log(n) > 2$, BIC penalizes more severely; this is pretty much always the case, since $e^2 = 7.3$ and it's rare to have less than 8 subjects.
As to which to use - there's debate about it; see e.g. Burnham and Anderson, 2002 Model Selection and Multimodel Inference (a good book); they also have an article about the comparison in Sociological Methods and Research | Why do AIC and BIC show inversed outputs? | AIC and BIC both penalize models for complexity, but they impose different penalties.
AIC = $2k - 2 \log(L)$ where $k$ is number of parameters and $L$ is likelihood.
BIC = $k*\log(n) - 2\log(L)$ whe | Why do AIC and BIC show inversed outputs?
AIC and BIC both penalize models for complexity, but they impose different penalties.
AIC = $2k - 2 \log(L)$ where $k$ is number of parameters and $L$ is likelihood.
BIC = $k*\log(n) - 2\log(L)$ where $n$ is number of subjects.
So, if $\log(n) > 2$, BIC penalizes more severely; this is pretty much always the case, since $e^2 = 7.3$ and it's rare to have less than 8 subjects.
As to which to use - there's debate about it; see e.g. Burnham and Anderson, 2002 Model Selection and Multimodel Inference (a good book); they also have an article about the comparison in Sociological Methods and Research | Why do AIC and BIC show inversed outputs?
AIC and BIC both penalize models for complexity, but they impose different penalties.
AIC = $2k - 2 \log(L)$ where $k$ is number of parameters and $L$ is likelihood.
BIC = $k*\log(n) - 2\log(L)$ whe |
38,790 | Why do AIC and BIC show inversed outputs? | My two cents on this topic: if you are really testing hypotheses then I would not use information theoretic approaches, but rather classical hypothesis testing approaches (i.e., I would use drop1 on res1 to do likelihood ratio tests). I personally prefer AIC to BIC in ecology because I think its logic more closely matches what we think about the systems: http://emdbolker.wikidot.com/blog:aic-vs-bic . But if I find myself trying to pick the model that most closely matches a "true" model with some number of non-zero parameters, I would hypothesis-test instead. | Why do AIC and BIC show inversed outputs? | My two cents on this topic: if you are really testing hypotheses then I would not use information theoretic approaches, but rather classical hypothesis testing approaches (i.e., I would use drop1 on r | Why do AIC and BIC show inversed outputs?
My two cents on this topic: if you are really testing hypotheses then I would not use information theoretic approaches, but rather classical hypothesis testing approaches (i.e., I would use drop1 on res1 to do likelihood ratio tests). I personally prefer AIC to BIC in ecology because I think its logic more closely matches what we think about the systems: http://emdbolker.wikidot.com/blog:aic-vs-bic . But if I find myself trying to pick the model that most closely matches a "true" model with some number of non-zero parameters, I would hypothesis-test instead. | Why do AIC and BIC show inversed outputs?
My two cents on this topic: if you are really testing hypotheses then I would not use information theoretic approaches, but rather classical hypothesis testing approaches (i.e., I would use drop1 on r |
38,791 | When to transform predictors in regression when response may be quadratic? | When you don't know the functional form ahead of time (which is a common setting) and you have no reason to assume it's linear, it's best to be flexible. If there were more levels of treatment you could fit a quadratic or restricted cubic spline shape, for example. For only 4 levels it may be best to assign 3 degrees of freedom to treatment using 3 dummy variables. | When to transform predictors in regression when response may be quadratic? | When you don't know the functional form ahead of time (which is a common setting) and you have no reason to assume it's linear, it's best to be flexible. If there were more levels of treatment you co | When to transform predictors in regression when response may be quadratic?
When you don't know the functional form ahead of time (which is a common setting) and you have no reason to assume it's linear, it's best to be flexible. If there were more levels of treatment you could fit a quadratic or restricted cubic spline shape, for example. For only 4 levels it may be best to assign 3 degrees of freedom to treatment using 3 dummy variables. | When to transform predictors in regression when response may be quadratic?
When you don't know the functional form ahead of time (which is a common setting) and you have no reason to assume it's linear, it's best to be flexible. If there were more levels of treatment you co |
38,792 | When to transform predictors in regression when response may be quadratic? | Why not look at a bivariate X-Y scatterplot in advance of running a regression. That'll show you the shape of the line or curve, especially if you have software that can give a lowess/loess fit (locally weighted smoothed fit).
As to interpretation, it'll no doubt be easier for you than for your audience, but if you do have a quadratic fit, then for each increment of one on the sq. rt. of X, Y will change by b, your coefficient.
If you really only have 4 levels of X, I agree with @Frank's point and would add that you might make your job easier by running an ANOVA instead of regression. Or, some software makes it easy to combine continuous and categorical predictors, fusing regression and anova into a general linear model without the need for dummy variables (if you use SPSS, search 'Unianova'). | When to transform predictors in regression when response may be quadratic? | Why not look at a bivariate X-Y scatterplot in advance of running a regression. That'll show you the shape of the line or curve, especially if you have software that can give a lowess/loess fit (loca | When to transform predictors in regression when response may be quadratic?
Why not look at a bivariate X-Y scatterplot in advance of running a regression. That'll show you the shape of the line or curve, especially if you have software that can give a lowess/loess fit (locally weighted smoothed fit).
As to interpretation, it'll no doubt be easier for you than for your audience, but if you do have a quadratic fit, then for each increment of one on the sq. rt. of X, Y will change by b, your coefficient.
If you really only have 4 levels of X, I agree with @Frank's point and would add that you might make your job easier by running an ANOVA instead of regression. Or, some software makes it easy to combine continuous and categorical predictors, fusing regression and anova into a general linear model without the need for dummy variables (if you use SPSS, search 'Unianova'). | When to transform predictors in regression when response may be quadratic?
Why not look at a bivariate X-Y scatterplot in advance of running a regression. That'll show you the shape of the line or curve, especially if you have software that can give a lowess/loess fit (loca |
38,793 | Computing $(X^TX)^{-1}X^Ty$ in OLS | Regarding your second question, here is a way to do this for $n=i$, for simplicity of notation. Let $\alpha = A_{nn}, \, a = (A_{1n},\dots, A_{n-1,n})^T$ and therefore
$$ A = \begin{pmatrix} \tilde A & a \\ a^T & \alpha \end{pmatrix}
$$
Also let $A^{-1}$ be partitioned in the same way,
$$ A^{-1} = \begin{pmatrix} \tilde C & c \\ c^T & \gamma \end{pmatrix}
$$
I understand you want $\tilde A^{-1}$ and have already computed $A^{-1}$. Set $d = \tilde A^{-1}a$ and $\delta = c^Ta$. These quantities already appear in $A^{-1}$, since
$$ A^{-1} = \begin{pmatrix} \tilde A^{-1} + \frac{1}{\alpha - \delta}dd^T & -\frac{1}{\alpha - \delta} d \\ -\frac{1}{\alpha - \delta} d^T & \frac{1}{\alpha - \delta} \end{pmatrix}
$$
as a direct calculation shows. Therefore,
$$
\tilde A^{-1} = \tilde C - \frac{1}{\alpha - \delta} dd^T = \tilde C - \frac{1}{\gamma}cc^T
$$
which is an $O(n^2)$ update of $A^{-1}$. | Computing $(X^TX)^{-1}X^Ty$ in OLS | Regarding your second question, here is a way to do this for $n=i$, for simplicity of notation. Let $\alpha = A_{nn}, \, a = (A_{1n},\dots, A_{n-1,n})^T$ and therefore
$$ A = \begin{pmatrix} \tilde A | Computing $(X^TX)^{-1}X^Ty$ in OLS
Regarding your second question, here is a way to do this for $n=i$, for simplicity of notation. Let $\alpha = A_{nn}, \, a = (A_{1n},\dots, A_{n-1,n})^T$ and therefore
$$ A = \begin{pmatrix} \tilde A & a \\ a^T & \alpha \end{pmatrix}
$$
Also let $A^{-1}$ be partitioned in the same way,
$$ A^{-1} = \begin{pmatrix} \tilde C & c \\ c^T & \gamma \end{pmatrix}
$$
I understand you want $\tilde A^{-1}$ and have already computed $A^{-1}$. Set $d = \tilde A^{-1}a$ and $\delta = c^Ta$. These quantities already appear in $A^{-1}$, since
$$ A^{-1} = \begin{pmatrix} \tilde A^{-1} + \frac{1}{\alpha - \delta}dd^T & -\frac{1}{\alpha - \delta} d \\ -\frac{1}{\alpha - \delta} d^T & \frac{1}{\alpha - \delta} \end{pmatrix}
$$
as a direct calculation shows. Therefore,
$$
\tilde A^{-1} = \tilde C - \frac{1}{\alpha - \delta} dd^T = \tilde C - \frac{1}{\gamma}cc^T
$$
which is an $O(n^2)$ update of $A^{-1}$. | Computing $(X^TX)^{-1}X^Ty$ in OLS
Regarding your second question, here is a way to do this for $n=i$, for simplicity of notation. Let $\alpha = A_{nn}, \, a = (A_{1n},\dots, A_{n-1,n})^T$ and therefore
$$ A = \begin{pmatrix} \tilde A |
38,794 | Computing $(X^TX)^{-1}X^Ty$ in OLS | To add to @onestop's answer, another efficient way is to use QR decomposition. The added benefit is that QR decomposition can be applied directly to $X$, and not to $X^TX$.
I think the QR decomposition can be made to work for your second question, it is definitely straightforward for column removal.
However the question is why do you need it? There are readily available libraries which perform these operations very efficiently. Do you want to reimplement them? As far as I understand there is a lot of non-trivial fine-tuning of code even if the algorithm is basically the best for the job, so chances are pretty high that you might not get full benefits by implementing algorithm which is supposedly theoretically superior.
Here is the link to the chapter in a book, which discusses modifications needed for solving the second question in case of QR decomposition. Although it states that the methods apply for least squares problems, it can be applied for system of linear equations.
I am pretty sure that this should be a standard problem, so maybe someone will give a more suitable reference. | Computing $(X^TX)^{-1}X^Ty$ in OLS | To add to @onestop's answer, another efficient way is to use QR decomposition. The added benefit is that QR decomposition can be applied directly to $X$, and not to $X^TX$.
I think the QR decompositi | Computing $(X^TX)^{-1}X^Ty$ in OLS
To add to @onestop's answer, another efficient way is to use QR decomposition. The added benefit is that QR decomposition can be applied directly to $X$, and not to $X^TX$.
I think the QR decomposition can be made to work for your second question, it is definitely straightforward for column removal.
However the question is why do you need it? There are readily available libraries which perform these operations very efficiently. Do you want to reimplement them? As far as I understand there is a lot of non-trivial fine-tuning of code even if the algorithm is basically the best for the job, so chances are pretty high that you might not get full benefits by implementing algorithm which is supposedly theoretically superior.
Here is the link to the chapter in a book, which discusses modifications needed for solving the second question in case of QR decomposition. Although it states that the methods apply for least squares problems, it can be applied for system of linear equations.
I am pretty sure that this should be a standard problem, so maybe someone will give a more suitable reference. | Computing $(X^TX)^{-1}X^Ty$ in OLS
To add to @onestop's answer, another efficient way is to use QR decomposition. The added benefit is that QR decomposition can be applied directly to $X$, and not to $X^TX$.
I think the QR decompositi |
38,795 | Computing $(X^TX)^{-1}X^Ty$ in OLS | The standard answer to your first question is Cholesky decomposition. To quote the Wikipedia article:
If $A$ is symmetric and positive definite, then we can solve $Ax = b$ [for $x$] by first computing the Cholesky decomposition $A = LL^\mathrm{T}$, then solving $Ly = b$ for $y$, and finally solving $L^\mathrm{T} x = y$ for $x$.
I'm not really clear what you're after in your second question. Doesn't a solution to the first question also provide a solution to the second? Surely it's not difficult computationally to remove a row and column from a matrix, and surely that's all the 'pre-proccessing' required?? | Computing $(X^TX)^{-1}X^Ty$ in OLS | The standard answer to your first question is Cholesky decomposition. To quote the Wikipedia article:
If $A$ is symmetric and positive definite, then we can solve $Ax = b$ [for $x$] by first computin | Computing $(X^TX)^{-1}X^Ty$ in OLS
The standard answer to your first question is Cholesky decomposition. To quote the Wikipedia article:
If $A$ is symmetric and positive definite, then we can solve $Ax = b$ [for $x$] by first computing the Cholesky decomposition $A = LL^\mathrm{T}$, then solving $Ly = b$ for $y$, and finally solving $L^\mathrm{T} x = y$ for $x$.
I'm not really clear what you're after in your second question. Doesn't a solution to the first question also provide a solution to the second? Surely it's not difficult computationally to remove a row and column from a matrix, and surely that's all the 'pre-proccessing' required?? | Computing $(X^TX)^{-1}X^Ty$ in OLS
The standard answer to your first question is Cholesky decomposition. To quote the Wikipedia article:
If $A$ is symmetric and positive definite, then we can solve $Ax = b$ [for $x$] by first computin |
38,796 | How to create one score from a mixed set of positive and negative variables? | You might consider u-scores as defined in [1] Wittkowski, K. M., Lee, E., Nussbaum, R., Chamian, F. N. and Krueger, J. G. (2004), Combining several ordinal measures in clinical studies. Statistics in Medicine, 23: 1579–1592. (PDF)
The basic idea is that for each observation you count how many observations there are compared to which it is definitely better (four variables lower, one higher), and how many are definitely worse, and then create a combined score. | How to create one score from a mixed set of positive and negative variables? | You might consider u-scores as defined in [1] Wittkowski, K. M., Lee, E., Nussbaum, R., Chamian, F. N. and Krueger, J. G. (2004), Combining several ordinal measures in clinical studies. Statistics in | How to create one score from a mixed set of positive and negative variables?
You might consider u-scores as defined in [1] Wittkowski, K. M., Lee, E., Nussbaum, R., Chamian, F. N. and Krueger, J. G. (2004), Combining several ordinal measures in clinical studies. Statistics in Medicine, 23: 1579–1592. (PDF)
The basic idea is that for each observation you count how many observations there are compared to which it is definitely better (four variables lower, one higher), and how many are definitely worse, and then create a combined score. | How to create one score from a mixed set of positive and negative variables?
You might consider u-scores as defined in [1] Wittkowski, K. M., Lee, E., Nussbaum, R., Chamian, F. N. and Krueger, J. G. (2004), Combining several ordinal measures in clinical studies. Statistics in |
38,797 | How to create one score from a mixed set of positive and negative variables? | Data or Theory Driven?
The first issue is whether you want the composite to be data driven or theory driven?
If you are wishing to form a composite variable, it is likely that you think that each component variable is important in measuring some overall domain.
In this case, you are likely going to prefer a theoretical set of weights. If, alternatively, you are interested in whatever is shared or common amongst the component variables, at the risk of not including one of the variables because it measures something that is orthogonal or less related to the remaining set, then you might want to explore data driven approaches.
This question maps on to the discussion in the structural equation modelling literature between reflective and formative measures
( e.g., see here).
Whatever you do it is important to align your measurement with your actual research question.
Theory Driven
If the composite is theoretically driven then you will want to form a weighted composite of the component variables where the weight assigned aligns with your theoretical weighting of the component.
If the variables are ordinal, then you'll have to think about how to scale the variable.
After scaling each component variable, you'll have to think about theoretical relative weighting and issues related to differential standard deviations of the variable.
One simple strategy is to convert all component variables into z-scores, and sum the z-scores.
If you have component variables, where some are positive and others are negative, then you'll need to reverse either just the negative or just the positive component variables.
I wrote a post on forming composites which addresses several scenarios for forming composites.
Theoretical driven approaches can be implemented easily in any statistical packages.
score.items in the psych package is one function that makes it a little easier, but it is limited.
You might just write your own equation using simple arithmetic, and perhaps the scale function.
Data Driven
If you are more interested in being data driven, then there are many possible approaches.
Taking the first principal component sounds like a reasonable idea.
If you have ordinal variables you might think about categorical PCA which would allow the component variables to be reweighted. This could automatically handle the quantification given the constraints you provide. | How to create one score from a mixed set of positive and negative variables? | Data or Theory Driven?
The first issue is whether you want the composite to be data driven or theory driven?
If you are wishing to form a composite variable, it is likely that you think that each comp | How to create one score from a mixed set of positive and negative variables?
Data or Theory Driven?
The first issue is whether you want the composite to be data driven or theory driven?
If you are wishing to form a composite variable, it is likely that you think that each component variable is important in measuring some overall domain.
In this case, you are likely going to prefer a theoretical set of weights. If, alternatively, you are interested in whatever is shared or common amongst the component variables, at the risk of not including one of the variables because it measures something that is orthogonal or less related to the remaining set, then you might want to explore data driven approaches.
This question maps on to the discussion in the structural equation modelling literature between reflective and formative measures
( e.g., see here).
Whatever you do it is important to align your measurement with your actual research question.
Theory Driven
If the composite is theoretically driven then you will want to form a weighted composite of the component variables where the weight assigned aligns with your theoretical weighting of the component.
If the variables are ordinal, then you'll have to think about how to scale the variable.
After scaling each component variable, you'll have to think about theoretical relative weighting and issues related to differential standard deviations of the variable.
One simple strategy is to convert all component variables into z-scores, and sum the z-scores.
If you have component variables, where some are positive and others are negative, then you'll need to reverse either just the negative or just the positive component variables.
I wrote a post on forming composites which addresses several scenarios for forming composites.
Theoretical driven approaches can be implemented easily in any statistical packages.
score.items in the psych package is one function that makes it a little easier, but it is limited.
You might just write your own equation using simple arithmetic, and perhaps the scale function.
Data Driven
If you are more interested in being data driven, then there are many possible approaches.
Taking the first principal component sounds like a reasonable idea.
If you have ordinal variables you might think about categorical PCA which would allow the component variables to be reweighted. This could automatically handle the quantification given the constraints you provide. | How to create one score from a mixed set of positive and negative variables?
Data or Theory Driven?
The first issue is whether you want the composite to be data driven or theory driven?
If you are wishing to form a composite variable, it is likely that you think that each comp |
38,798 | How to create one score from a mixed set of positive and negative variables? | For a non-ordinal measure, you could try MDS (multi-dimensional scaling). This can be done easily in R. This will try to arrange the points on a line (1d in your case) in such a way that distances between points will be preserved.
Some general comments: as you probably realize, the question is pretty vague, and not much can be said without knowing more about the data. For example, normalizing the variables (to zero mean and unit variance) may or may not be appropriate; weighing all variable equally may or may not be appropriate; etc. If this is not an exploratory analysis and you do have some 'correct' score in mind, then it may be appropriate to learn a set of weights either on a different dataset, or on a subset of your current dataset, and using these weights instead. | How to create one score from a mixed set of positive and negative variables? | For a non-ordinal measure, you could try MDS (multi-dimensional scaling). This can be done easily in R. This will try to arrange the points on a line (1d in your case) in such a way that distances bet | How to create one score from a mixed set of positive and negative variables?
For a non-ordinal measure, you could try MDS (multi-dimensional scaling). This can be done easily in R. This will try to arrange the points on a line (1d in your case) in such a way that distances between points will be preserved.
Some general comments: as you probably realize, the question is pretty vague, and not much can be said without knowing more about the data. For example, normalizing the variables (to zero mean and unit variance) may or may not be appropriate; weighing all variable equally may or may not be appropriate; etc. If this is not an exploratory analysis and you do have some 'correct' score in mind, then it may be appropriate to learn a set of weights either on a different dataset, or on a subset of your current dataset, and using these weights instead. | How to create one score from a mixed set of positive and negative variables?
For a non-ordinal measure, you could try MDS (multi-dimensional scaling). This can be done easily in R. This will try to arrange the points on a line (1d in your case) in such a way that distances bet |
38,799 | How to create one score from a mixed set of positive and negative variables? | I am sorry, as it may not be straight answer to your question, by if you are using this "total score" as a predictor of something why dont you try regression and evaluate the results with the AUC of ROC ?
or the other way, maybe user Neural networks / Random Forest / Support Vector machines on them to predict given outcome ?
Regards Luke | How to create one score from a mixed set of positive and negative variables? | I am sorry, as it may not be straight answer to your question, by if you are using this "total score" as a predictor of something why dont you try regression and evaluate the results with the AUC of R | How to create one score from a mixed set of positive and negative variables?
I am sorry, as it may not be straight answer to your question, by if you are using this "total score" as a predictor of something why dont you try regression and evaluate the results with the AUC of ROC ?
or the other way, maybe user Neural networks / Random Forest / Support Vector machines on them to predict given outcome ?
Regards Luke | How to create one score from a mixed set of positive and negative variables?
I am sorry, as it may not be straight answer to your question, by if you are using this "total score" as a predictor of something why dont you try regression and evaluate the results with the AUC of R |
38,800 | What is the probability of picking p primes from n random numbers? | There are 203,280,221 primes less than $2^{32}$. (Source). So the probability that a random 32-bit number is prime is $203,280,221 / 2^{32} \approx 0.04733$. Assuming you want selection with replacement, i.e. the same number can be picked more than once, the probability of picking $p$ primes from $n$ 32-bit random numbers is, from the probability mass function of the binomial distribution,
$$\frac {n!}{p!(n-p)!} 0.04733^p (1-0.04733)^{n-p} . $$ | What is the probability of picking p primes from n random numbers? | There are 203,280,221 primes less than $2^{32}$. (Source). So the probability that a random 32-bit number is prime is $203,280,221 / 2^{32} \approx 0.04733$. Assuming you want selection with replaceme | What is the probability of picking p primes from n random numbers?
There are 203,280,221 primes less than $2^{32}$. (Source). So the probability that a random 32-bit number is prime is $203,280,221 / 2^{32} \approx 0.04733$. Assuming you want selection with replacement, i.e. the same number can be picked more than once, the probability of picking $p$ primes from $n$ 32-bit random numbers is, from the probability mass function of the binomial distribution,
$$\frac {n!}{p!(n-p)!} 0.04733^p (1-0.04733)^{n-p} . $$ | What is the probability of picking p primes from n random numbers?
There are 203,280,221 primes less than $2^{32}$. (Source). So the probability that a random 32-bit number is prime is $203,280,221 / 2^{32} \approx 0.04733$. Assuming you want selection with replaceme |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.