All About Statistics Thu, 25 Sep 2014 15:53:47 +0000 en-US hourly 1 http://wordpress.org/?v=3.4.2 statsblogshttps://feedburner.google.com Estimating Generalization Error with the PRESS statistic http://feedproxy.google.com/~r/statsblogs/~3/_tRI-hg13U4/ /2014/09/25/estimating-generalization-error-with-the-press-statistic/#comments Thu, 25 Sep 2014 15:53:47 +0000 Nina Zumel http://www.win-vector.com/blog/?p=2846 As we’ve mentioned on previous occasions, one of the defining characteristics of data science is the emphasis on the availability of “large” data sets, which we define as “enough data that statistical efficiency is not a concern” (note that a “large” data set need not be “big data,” however you choose to define it). In […]

The post Estimating Generalization Error with the PRESS statistic appeared first on All About Statistics.

]]>
(This article was originally published at Win-Vector Blog » Statistics, and syndicated at StatsBlogs.)

As we’ve mentioned on previous occasions, one of the defining characteristics of data science is the emphasis on the availability of “large” data sets, which we define as “enough data that statistical efficiency is not a concern” (note that a “large” data set need not be “big data,” however you choose to define it). In particular, we advocate the use of hold-out data to evaluate the performance of models.

There is one caveat: if you are evaluating a series of models to pick the best (and you usually are), then a single hold-out set is strictly speaking not enough. Hastie, et.al, say it best:

Ideally, the test set should be kept in a “vault,” and be brought out only at the end of the data analysis. Suppose instead that we use the test-set repeatedly, choosing the model with smallest test-set error. Then the test set error of the final chosen model will underestimate the true test error, sometimes substantially.

– Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, 2nd edition.

The ideal way to select a model from a set of candidates (or set parameters for a model, for example the regularization constant) is to use a training set to train the model(s), a calibration set to select the model or choose parameters, and a test set to estimate the generalization error of the final model.

In many situations, breaking your data into three sets may not be practical: you may not have very much data, or the the phenomena you’re interested in are rare enough that you need a lot of data to detect them. In those cases, you will need more statistically efficient estimates for generalization error or goodness-of-fit. In this article, we look at the PRESS statistic, and how to use it to estimate generalization error and choose between models.

The PRESS Statistic

You can think of the PRESS statistic as an “adjusted sum of squared error (SSE).” It is calculated as

NewImage

Where n is the number of data points in the training set, yi is the outcome of the ith data point, and fi is the prediction for yi from a model that is trained using all the data except the ith data point. In other words, the PRESS statistic is the SSE from hold-one-out cross-validation; it tries to estimate how the model will perform on hold-out data, using only in-sample data.

For example, if you wanted to calculate the PRESS statistic for linear regression models in R, you could do it this way (though I wouldn’t recommend it):

# For explanation purposes only -
# DO NOT implement PRESS this way
brutePRESS.lm = function(fmla, dframe, outcome) {
  npts = dim(dframe)[1] 
  ssdev = 0
  for(i in 1:npts) {
    # a data frame with all but the ith row
    d = dframe[-i,]
    # build a model using all but pt i
    m = lm(fmla, data=d)
    # then predict outcome[i]
    pred = predict(m, newdata=dframe[i,]) 
    # sum the squared deviations
    ssdev = ssdev + (pred - outcome[i])^2
  }
  ssdev
}

We have implemented a couple of helper functions to calculate the PRESS statistic (and related measures) for linear regression models more efficiently. You can find the code here. The function hold1OutLMPreds(fmla, dframe) returns the vector f, where f[i] is the prediction on the ith row of dframe, when fitting the linear regression model described by fmla on dframe[-i,]. The function hold1OutMeans(y) returns a vector g where g[i] = mean(y[-i]). With these function, you can efficiently calculate the PRESS statistic for a linear regression model:

hopreds = hold1OutLMPreds(fmla, dframe)
devs = y-hopreds
PRESS = sum(devs^2)

One disadvantage of the SSE (and the PRESS) is that they are dependent on the data size; you can’t compare a single model’s performance across data sets of different size. You can remove that dependency by going to the root mean squared error (RMSE): rmse = sqrt(sse/n), where n is the size of the data set. You can also calculate an equivalent “root mean PRESS” statistic:

n = length(y)
hopreds = hold1OutLMPreds(fmla, dframe)
devs = y-hopreds
rmPRESS = sqrt(mean(devs^2))

And you can also define a “PRESS R-squared”:

n = length(y)
hopreds = hold1OutLMPreds(fmla, dframe)
homeans = hold1OutMeans(y)
devs = y-hopreds
dely = y-homeans

PRESS = sum(devs^2)
PRESS.r2= 1 - (PRESS/sum(dely^2))

The “PRESS R-squared” is one minus the ratio of the model’s PRESS over the “PRESS of y’s mean value;” it adjusts the estimate of how much variation the model explains by using 1-fold cross validation rather than adjusting for the model’s degrees of freedom (as the more standard adjusted R-square does).

You might also consider defining a PRESS R-squared using the in-sample total error (y-mean(y)) instead of the 1-hold-out mean; we decided on the latter in an “apples-to-apples” spirit. Note also that PRESS R-squared can be negative if the model is very poor.

An Example

Let’s imagine a situation where we want to predict a quantity y, and we have many many potential inputs to use in our prediction. Some of these inputs are truly correlated with y; some of them are not. Of course, we don’t know which are which. We have some training data with which to build models, and we will get (but don’t yet have) hold-out data to evaluate the final model. How might we proceed?

First, let’s create a process to simulate this situation:

# build a data frame with pure noise columns
# and columns weakly correlated with y
buildExample1 <- function(nRows) {
  nNoiseCols <- 300
  nCorCols <- 20
  copyDegree <- 0.1
  noiseMagnitude <- 0.1
  d <- data.frame(y=rnorm(nRows))
  for(i in 1:nNoiseCols) {
    nm <- paste('noise',i,sep='_')
    d[,nm] <- noiseMagnitude*rnorm(nRows) + 
          ifelse(runif(nRows)<=copyDegree, rnorm(nRows), 0)
  }
  for(i in 1:nCorCols) {
    nm <- paste('cor',i,sep='_')
    d[,nm] <- noiseMagnitude*rnorm(nRows) + 
        ifelse(runif(nRows)<=copyDegree,d$y,0)
  }
  d
}

This function will produce a dataset of nRows rows with 20 columns that are weakly correlated (called cor_1, cor_2...) with y and 300 columns (noise_1, noise_2...) that are independent of y. The process is designed so that the noise columns and the correlated columns have similar magnitudes and variances. The outcome can be expressed as a linear combination of the correlated inputs, so a linear regression model should give reasonable predictions.

Let's suppose we have two candidate models: one which uses all the variables, and one which magically uses only the intentionally correlated variables.

set.seed(22525)
train = buildExample1(1000)

output = "y"
inputs = setdiff(colnames(train), output)
truein = inputs[grepl("^cor",inputs)]

# all variables, including noise
# (noisy model)
fmla1 = paste(output, "~", paste(inputs, collapse="+"))
mod1 = lm(fmla1, data=train)

# only true inputs
# (clean model)
fmla2 = paste(output, "~", paste(truein, collapse="+"))
mod2 = lm(fmla2, data=train)

We can extract all the model coefficients that lm() deemed significant to p < 0.05 (that is, all the coefficients that are marked with at least one "*" in the model summary).

# 0.05 = "*" in the model summary
sigCoeffs = function(model, pmax=0.05) {
  cmat = summary(model)$coefficients
  pvals = cmat[,4]
  plo = names(pvals)[pvals < pmax]
  plo
}

# significant coefficients in the noisy model
sigCoeffs(mod1)
##  [1] "noise_41"  "noise_59"  "noise_66"  "noise_117" "noise_207"
##  [6] "noise_256" "noise_279" "noise_280" "cor_1"     "cor_2"    
## [11] "cor_3"     "cor_4"     "cor_5"     "cor_6"     "cor_7"    
## [16] "cor_8"     "cor_9"     "cor_10"    "cor_11"    "cor_12"   
## [21] "cor_13"    "cor_14"    "cor_15"    "cor_16"    "cor_17"   
## [26] "cor_18"    "cor_19"    "cor_20"

In other words, several of the noise inputs appear to be correlated with the output in the training data, just by chance. This means that the noisy model has overfit the data. Can we detect that? Let's look at the SSE and the PRESS:

##          name   sse PRESS
## 1 noisy model 203.3 448.6
## 2 clean model 285.8 306.8

Looking at the in-sample SSE, the noisy model looks better than the clean model; the PRESS says otherwise. We can see the same thing if we look at the R-squared style measures:

##          name     R2  R2adj PRESSr2
## 1 noisy model 0.7931 0.6956  0.5442
## 2 clean model 0.7091 0.7031  0.6884

Again, R-squared makes the noisy model look better than the clean model. The adjusted R-squared correctly indicates that the additional variables in the noisy model do not improve the fit, and slightly prefers the clean model. The PRESS R-squared identifies the clean model as the better model, with a much larger margin of difference than the adjusted R-squared.

The PRESS statistic versus Hold-out Data

Of course, while the PRESS statistic is statistically efficient, it is not always computationally efficient, especially with modeling techniques other than linear regression. The calculation of the adjusted R-squared is not computationally demanding, and it also identified the better model in our experiment. One could ask, why not just use adjusted R-squared?

One reason is that the PRESS statistic is attempting to directly model future predictive performance. Our experiment suggests that it shows clearer distinctions between the models than the adjusted R-squared. But how well does the PRESS statistic estimate the "true" generalization error of a model?

To test this, we will hold the ground truth (that is, the data generation process) and the training set fixed. We will then repeat generating test sets, measuring the RMSE of the models' predictions against the test sets, and compare them to the training RMSE and root mean PRESS. This is akin to a situation where the training data and model fitting are accomplished facts, and we are hypothesizing possible future applications of the model.

Specifically, we used buildExample1() to generate one hundred tests sets of size 100 (10% the size of the training set) and one hundred tests sets of size 1000 (the size of the training set). We then evaluated both the clean model and the noisy model against all the test sets and compared the distributions of the hold-out root mean squared error (RMSE) against the in-sample RMSE and PRESS statistics. The results are shown below.

NewImage

For each plot, the solid black vertical line is the mean of the distribution of test RMSE; we can assume that the observed mean is a good approximation to the "true" expected RMSE of the model. Not surprisingly, a smaller test set size leads to more variance in the observed RMSE, but after 100 trials, both the n=100 and n=1000 hold out sets lead to similar estimates of the expected RMSE (just under 0.7 for the noisy model, just under 0.6 for the clean model.

The dashed red lines give the root mean PRESS of both models on the training data, and the dashed blue lines give each models' training set RMSE. For both the noisy and clean models, the root mean PRESS gives a better estimate of the models' expected RMSE than the training set RMSE -- dramatically so with the noisy, overfit model.

Note, however, that in this experiment, a single hold-out set reliably preferred the clean model to the noisy one (that is, the hold-out SSE was always greater for the noisy model than the clean one when both models were applied to the same test data). The moral of the story: use hold-out data (both calibration and test sets) when that is feasible. When data is at a premium, then try more statistically efficient metrics like the PRESS statistic to "stretch" the data that you have.



Please comment on the article here: Win-Vector Blog » Statistics

The post Estimating Generalization Error with the PRESS statistic appeared first on All About Statistics.

]]>
/2014/09/25/estimating-generalization-error-with-the-press-statistic/feed/ 0 /2014/09/25/estimating-generalization-error-with-the-press-statistic/
Waic for time series http://feedproxy.google.com/~r/statsblogs/~3/J_PdT_QSfXw/ /2014/09/25/waic-for-time-series/#comments Thu, 25 Sep 2014 13:24:08 +0000 Andrew http://andrewgelman.com/?p=23486

Helen Steingroever writes: I’m currently working on a model comparison paper using WAIC, and would like to ask you the following question about the WAIC computation: I have data of one participant that consist of 100 sequential choices (you can think of these data as being a time series). I want to compute the WAIC […]

The post Waic for time series appeared first on Statistical Modeling, Causal Inference, and Social Science.

The post Waic for time series appeared first on All About Statistics.

]]>
(This article was originally published at Statistical Modeling, Causal Inference, and Social Science, and syndicated at StatsBlogs.)

Helen Steingroever writes:

I’m currently working on a model comparison paper using WAIC, and
would like to ask you the following question about the WAIC computation:

I have data of one participant that consist of 100 sequential choices (you can think of these data as being a time series). I want to compute the WAIC for these data. Now I’m wondering how I should compute the predictive density. I think there are two possibilities:

(1) I compute the predictive density of the whole sequence (i.e., I consider the whole sequence as one data point, which means that n=1 in Equations (11) – (12) of your 2013 Stat Comput paper.)
(2) I compute the predictive density for each choice (i.e., I consider each choice as one data point, which means that n=# choices in Equations (11) – (12) of your 2013 Stat Comput paper.)

My quick thought was that Waic is an approximation to leave-one-out cross-validation and this computation gets more complicated with correlated data.

But I passed the question on to Aki, the real expert on this stuff. Aki wrote:

This a interesting question and there is no simple answer.

First we should consider what is your predictive goal:
(1) predict whole sequence for another participant
(2) predict a single choice given all other choices
or
(3) predict the next choice given the choices in the sequence so far?

If your predictive goal is

(1) then you should note that WAIC is based on an asymptotic argument and it is not generally accurate with n=1. Watanabe has said (personal communication) that he thinks that this is not sensible scenario for WAIC, but if (1) is really your prediction goal, then I think that this is might be best you can do. It seems that when n is small, WAIC will usually underestimate the effective complexity of the model, and thus would give over-optimistic performance estimates for more complex models.

(2) WAIC should work just fine here (unless your model says that there is no dependency between the choices, ie. having 100 separate models with each having n=1). Correlated data here means just that it is easier to predict a choice if you know the previous choices and the following choices. This may make difference between some models small compared to scenario (1).

(3) WAIC can’t handle this, and you would need to use a specific form of cross-validation (I think I should write a paper on this).

The post Waic for time series appeared first on Statistical Modeling, Causal Inference, and Social Science.



Please comment on the article here: Statistical Modeling, Causal Inference, and Social Science

The post Waic for time series appeared first on All About Statistics.

]]>
/2014/09/25/waic-for-time-series/feed/ 0 /2014/09/25/waic-for-time-series/
Multiple Tests, an Introduction http://feedproxy.google.com/~r/statsblogs/~3/NzqAJ_uOdbk/ /2014/09/24/multiple-tests-an-introduction/#comments Wed, 24 Sep 2014 20:12:30 +0000 Arthur Charpentier http://freakonometrics.hypotheses.org/?p=16965 Last week, a student asked me about multiple tests. More precisely, she ran an experience over – say – 20 weeks, with the same cohort of – say – 100 patients. An we observe some size=100 nb=20 set.seed(1) X=matrix(rnorm(size*nb),size,nb) (here, I just generate some fake data). I can visualize some trajectories, over the 20 weeks, library(RColorBrewer) cl1=brewer.pal(12,"Set3")[12] cl2=brewer.pal(8,"Set2")[2:7] cl=c(cl1,cl2) boxplot(X) for(i in 1:length(cl)){ lines(1:20,X[i,],type="b",col=cl[i]) }   She wanted to compare the averages, over the experiments. boxplot(X) for(i in 1:length(cl)){ lines(1:20,X[i,],type="b",col=cl[i]) } The question is […]

The post Multiple Tests, an Introduction appeared first on All About Statistics.

]]>
(This article was originally published at Freakonometrics » Statistics, and syndicated at StatsBlogs.)

Last week, a student asked me about multiple tests. More precisely, she ran an experience over – say – 20 weeks, with the same cohort of – say – 100 patients. An we observe some http://latex.codecogs.com/gif.latex?X_{i,t}

size=100
nb=20
set.seed(1)
X=matrix(rnorm(size*nb),size,nb)

(here, I just generate some fake data). I can visualize some trajectories, over the 20 weeks,

library(RColorBrewer)
cl1=brewer.pal(12,"Set3")[12]
cl2=brewer.pal(8,"Set2")[2:7]
cl=c(cl1,cl2)
boxplot(X)
for(i in 1:length(cl)){
lines(1:20,X[i,],type="b",col=cl[i])  }

http://f-origin.hypotheses.org/wp-content/blogs.dir/253/files/2014/09/Selection_585.png

 

She wanted to compare the averages, over the experiments.

boxplot(X)
for(i in 1:length(cl)){
lines(1:20,X[i,],type="b",col=cl[i])  }

The question is what do you want to test ? Is it

http://latex.codecogs.com/gif.latex?H_0:\forall%20i,j\in\{1,\cdots,%20T\},%20\mu_i=\mu_j

versus

http://latex.codecogs.com/gif.latex?H_1:\exists%20i,j\in\{1,\cdots,%20T\},%20\mu_i\neq%20\mu_j

Because that one might be not very informative (if we reject http://latex.codecogs.com/gif.latex?H_0, we don’t really know why). Here, I did consider completely independent observations, over individuals, and over time. Nevertheless, if we perform 190 tests on pairs, we should not be suprised – even if http://latex.codecogs.com/gif.latex?H_0 is valid – that we reject it many times !

> P=NULL
> for(i in 1:(nb-1)){ for(j in (i+1):nb){
+ P=c(P,t.test(X[,i],X[,j])$p.value) }}
> mean(P>.05)
[1] 0.9368421

i.e. for 12 pairs, we reject the assumption of identical mean. Even if that assumption is true, here. That’s the problem with multiple tests.

Actually, observe that over those 190 tests, the http://latex.codecogs.com/gif.latex?p-values are uniformly distributed over the unit interval. Thus, for (almost) 95% of the tests, the http://latex.codecogs.com/gif.latex?p-value exceeds 5%.

Now, what if we relax the assumption of independence ? Here, we need to be more specific. A first idea might be to assume that

http://latex.codecogs.com/gif.latex?X_{i,t}=\mu_t%20+%20\varepsilon_{i,t}

for some trend http://latex.codecogs.com/gif.latex?\mu_t. We can actually assume that the trend depends on the individuals, and write, for instance,

http://latex.codecogs.com/gif.latex?X_{i,t}=\alpha_i%20+%20\beta_i%20t%20+%20\varepsilon_{i,t}

Standard regression techniques can be considered, under those models. We’ll probably discuss that point before the end of this year.

My point was the following : if the assume that

http://latex.codecogs.com/gif.latex?\boldsymbol{X}_i=(X_{i,1},\cdots,X_{i,T})

consist of independent observations, where all http://latex.codecogs.com/gif.latex?X_{i,t}‘s are assumed to be independent, if we use pairwise comparison tests for the means, in 95% of the tests, the http://latex.codecogs.com/gif.latex?p-value exceeds 5%, and in 90% of the tests, the http://latex.codecogs.com/gif.latex?p-value exceeds 10%. That the interpreation of the property that http://latex.codecogs.com/gif.latex?p-values are uniformly distributed on the unit interval. Now, what if we relax the independence assumption. What if obsevations were – somehow – correlated.

A first idea could be to consider a linear trend,

X=matrix(rnorm(size*nb),size,nb)
T=t(matrix((1:nb)/nb*r,nb,size))
X=X+T*a

Here, we still compute pairwise comparison tests

> P=NULL
> for(i in 1:(nb-1)){ for(j in (i+1):nb){
+ P=c(P,t.test(X[,i],X[,j])$p.value) }}

and we counts the number of pairs where the http://latex.codecogs.com/gif.latex?p-values exceeds some given values

PV[1]=mean(P>.025)
PV[2]=mean(P>.05)
PV[3]=mean(P>.075)
PV[4]=mean(P>.1)
PV[5]=mean(P>.125)
PV[6]=mean(P>.15)

If we look at the proportions, as a function of the slope, we have the following graph

In the middle, we have the independent case, e.g. 97.5% of the the http://latex.codecogs.com/gif.latex?p-values exceeds 2.5% – the upper curve. But, as the slope increase (or decrease), the proportion decreases. With a 0.2 slope, 90% of the the http://latex.codecogs.com/gif.latex?p-values exceeds 2.5%.

One can also assume that

http://latex.codecogs.com/gif.latex?\boldsymbol{X}_i=(X_{i,1},\cdots,X_{i,T})

is some time series. An autoregressive one, for instance,

http://latex.codecogs.com/gif.latex?X_{i,t}=\varphi%20X_{i,t-1}+\varepsilon_{i,t}

Here we use to following code to generate that vector

autoreg=function(n,r){
M=matrix(1,n,n)
for(i in 1:(n-2)){
diag(M[(i+1):n,1:(n-i)])=r^i
diag(M[1:(n-i),(i+1):n])=r^i
}
M[1,n]=M[n,1]=r^(i+1)
return(M)
}
S=autoreg(nb,r)
library(mnormt)
X=rmnorm(size,varcov=S)

The graph below is the evolution of the proportion of http://latex.codecogs.com/gif.latex?p-values exceeding some threshold, as a function of the autoregressive coefficient.

The value on the left is the independent case (and http://latex.codecogs.com/gif.latex?p-values are uniformly distributed). The stronger the autocorrelation, the larger the proportion of http://latex.codecogs.com/gif.latex?p-values exceeding any value.

Finally, consider the case where components of vector

http://latex.codecogs.com/gif.latex?\boldsymbol{X}_i=(X_{i,1},\cdots,X_{i,T})

are exchangeable.

S=matrix(r,nb,nb)
diag(S)=1
library(mnormt)
X=rmnorm(size,M,varcov=S)

In that case, we have the following graph, with the proportion of http://latex.codecogs.com/gif.latex?p-values exceeding some value, as the function of the correlation of (any) pair http://latex.codecogs.com/gif.latex?(X_{i,s},X_{i,t}).

This is the idea that is used in any correction-type method, with multiple tests, for instance Bonferroni correction. When a run http://latex.codecogs.com/gif.latex?m tests, instead of comparing the http://latex.codecogs.com/gif.latex?p-value with http://latex.codecogs.com/gif.latex?\alpha, we use a correction on http://latex.codecogs.com/gif.latex?\alpha, http://latex.codecogs.com/gif.latex?\alpha(m). But as we can see here, it will depend on the kind of dependence we assume there might be.

Next time, I will discuss my student’s data, see what could be said.



Please comment on the article here: Freakonometrics » Statistics

The post Multiple Tests, an Introduction appeared first on All About Statistics.

]]>
/2014/09/24/multiple-tests-an-introduction/feed/ 0 /2014/09/24/multiple-tests-an-introduction/
Study published in 2011, followed by successful replication in 2003 [sic] http://feedproxy.google.com/~r/statsblogs/~3/wpaHR7gWLv4/ /2014/09/24/study-published-in-2011-followed-by-successful-replication-in-2003-sic/#comments Wed, 24 Sep 2014 13:14:39 +0000 Andrew http://andrewgelman.com/?p=23552

This one is like shooting fish in a barrel but sometimes the job just has to be done. . . . The paper is by Daryl Bem, Patrizio Tressoldi, Thomas Rabeyron, and Michael Duggan, it’s called “Feeling the Future: A Meta-Analysis of 90 Experiments on the Anomalous Anticipation of Random Future Events,” and it begins […]

The post Study published in 2011, followed by successful replication in 2003 [sic] appeared first on Statistical Modeling, Causal Inference, and Social Science.

The post Study published in 2011, followed by successful replication in 2003 [sic] appeared first on All About Statistics.

]]>
(This article was originally published at Statistical Modeling, Causal Inference, and Social Science, and syndicated at StatsBlogs.)

bullwinkle_ball

This one is like shooting fish in a barrel but sometimes the job just has to be done. . . .

The paper is by Daryl Bem, Patrizio Tressoldi, Thomas Rabeyron, and Michael Duggan, it’s called “Feeling the Future: A Meta-Analysis of 90 Experiments on the Anomalous Anticipation of Random Future Events,” and it begins like this:

In 2011, the Journal of Personality and Social Psychology published a report of nine experiments purporting to demonstrate that an individual’s cognitive and affective responses can be influenced by randomly selected stimulus events that do not occur until after his or her responses have already been made and recorded (Bem, 2011). To encourage exact replications of the experiments, all materials needed to conduct them were made available on request. We can now report a meta-analysis of 90 experiments from 33 laboratories in 14 different countries which yielded an overall positive effect in excess of 6 sigma . . . A Bayesian analysis yielded a Bayes Factor of 7.4 × 10-9 . . . An analysis of p values across experiments implies that the results were not a product of “p-hacking” . . .

Actually, no.

There is a lot of selection going on here. For example, they report that 57% (or, as they quaintly put it, “56.6%”) of the experiments had been published in peer reviewed journals or conference proceedings. Think of all the unsuccessful, unpublished replications that didn’t get caught in the net. But of course almost any result that happened to be statistically significant would be published, hence a big bias. Second, they go back and forth, sometimes considering all replications, other times ruling some out as not following protocol. At one point they criticize internet experiments which is fine, but again it’s more selection because if the results from the internet experiments had looked good, I don’t think we’d be seeing that criticism. Similarly, we get statements like, “If we exclude the 3 experiments that were not designed to be replications of Bem’s original protocol . . .”. This would be a lot more convincing if they’d defined their protocols clearly ahead of time.

I question the authors’ claims that various replications are “exact.” Bem’s paper was published in 2011, so how can it be that experiments performed as early as 2003 are exact replications? That makes no sense. Just to get an idea of what was going on, I tried to find one of the earlier studies that was stated to be an exact replication. I looked up the paper by Savva et al. (2005), “Further testing of the precognitive habituation effect using spider stimuli.” I could not find this one but I found a related one, also on spider stimuli. In what sense is this an “exact replication” of Bem? I looked at the Bem (2011) paper, searched on “spider,” and all I could find is a reference to Savva et al.’s 2004 work.

This baffled me so I went to the paper linked above and searched on “exact replication” to see how they defined the term. Here’s what I found:

“To qualify as an exact replication, the experiment had to use Bem’s software without any procedural modifications other than translating on-screen instructions and stimulus words into a language other than English if needed.”

I’m sorry, but, no. Using the same software is not enough to qualify as an “exact replication.”

This issue is central to the paper at hand. For example, there is a discussion on page 18 on “the importance of exact replications”: “When a replication succeeds, it logically implies that every step in the replication ‘worked’ . . .”

Beyond this, the individual experiments have multiple comparisons issues, just as did the Bem (2011) paper. We see very few actual preregistrations, and my impression is that when something counts as a successful replication there is still a lot of wiggle room regarding data inclusion rules, which interactions to study, etc.

Who cares?

The ESP context makes this all look like a big joke, but the general problem of researchers creating findings out of nothing, that seems to be a big issue in social psychology and other research areas involving noisy measurements. So I think it’s worth holding a firm line on this sort of thing. I have a feeling that the authors of this paper think that if you have a p-value or Bayes factor of 10^-9 then your evidence is pretty definitive, even if some nitpickers can argue on the edges about this or that. But it doesn’t work that way. The garden of forking paths is multiplicative, and with enough options it’s not so hard to multiply up to factors of 10^-9 or whatever. And it’s not like you have to be trying to cheat; you just keep making reasonable choices given the data you see, and you can get there, no problem. Selecting ten-year-old papers and calling them “exact replications” is one way to do it.

P.S. I found the delightful image above by googling *bullwinkle crystal ball* but I can’t seem to track down who to give the credit to. Jay Ward, Alex Anderson, and Bill Scott, I suppose. It doesn’t seem to matter so much who actually got the screenshot and posted it on the web.

The post Study published in 2011, followed by successful replication in 2003 [sic] appeared first on Statistical Modeling, Causal Inference, and Social Science.



Please comment on the article here: Statistical Modeling, Causal Inference, and Social Science

The post Study published in 2011, followed by successful replication in 2003 [sic] appeared first on All About Statistics.

]]>
/2014/09/24/study-published-in-2011-followed-by-successful-replication-in-2003-sic/feed/ 0 /2014/09/24/study-published-in-2011-followed-by-successful-replication-in-2003-sic/
Book of the year http://feedproxy.google.com/~r/statsblogs/~3/XbxRPuDINp8/ /2014/09/24/book-of-the-year/#comments Wed, 24 Sep 2014 12:40:00 +0000 Gianluca Baio /?guid=b5c585d6c182937670aaedcae482c27b The next issue of Significance (it will be a December double issue) will feature a festive version of the usual book review section. Readers and contributors can nominate their favourite statistics books of the year and alongside the nominati...

The post Book of the year appeared first on All About Statistics.

]]>
(This article was originally published at Gianluca Baio's blog, and syndicated at StatsBlogs.)

The next issue of Significance (it will be a December double issue) will feature a festive version of the usual book review section. 

Readers and contributors can nominate their favourite statistics books of the year and alongside the nomination, we're looking for a 100-word explanation of why they recommend it.

Full details are on the Significance website.





Please comment on the article here: Gianluca Baio's blog

The post Book of the year appeared first on All About Statistics.

]]>
/2014/09/24/book-of-the-year/feed/ 0 /2014/09/24/book-of-the-year/
Designing a quantile bin plot http://feedproxy.google.com/~r/statsblogs/~3/aoqg5BF7Nsw/ /2014/09/24/designing-a-quantile-bin-plot/#comments Wed, 24 Sep 2014 09:27:03 +0000 Rick Wicklin http://blogs.sas.com/content/iml/?p=12135 While at JSM 2014 in Boston, a statistician asked me whether it was possible to create a "customized bin plot" in SAS. When I asked for more information, she told me that she has a large data set. She wants to visualize the data, but a scatter plot is not […]

The post Designing a quantile bin plot appeared first on All About Statistics.

]]>
(This article was originally published at The DO Loop, and syndicated at StatsBlogs.)

While at JSM 2014 in Boston, a statistician asked me whether it was possible to create a "customized bin plot" in SAS. When I asked for more information, she told me that she has a large data set. She wants to visualize the data, but a scatter plot is not very useful because of severe overplotting. I suggested several visualization options:

Unfortunately, she rejected these standard visualizations. She and her colleagues had decided that they needed a new type of binned plot that is constructed as follows:

  1. Divide the X and Y variables into quantiles. This creates a nonuniform grid in (X,Y) space. Each vertical strip and each horizontal strip contain about the same number of points. In particular, she wanted to use deciles, so that each strip contains about 10% of the total number of observations.
  2. The resulting grid has rectangles that vary in size, but you can still count the number of points in each rectangular bin.
  3. For each bin, put a marker at the mean X and mean Y value of the observations within the bin.

This is exactly the sort of computation that SAS/IML is intended for: a custom algorithm for multivariate data that is not built into any SAS procedure. From previous blog posts, I already have many of the building blocks for this algorithm:

The following program reads the Sashelp.bweight data and loads the birth weight of 50,000 babies and the relative weight gain of their mothers. The subsequent SAS/IML statements carry out the algorithm that the statistician requested:

proc iml;
use sashelp.bweight;                     /* read birthweight data */
   read all var {momwtgain weight} into Z;
close;
 
start bin2D(u, cutX, cutY);         /* define 2-D bin function */
   bX = bin(u[,1], cutX);           /* bins in X direction: 1,2,...,kx */
   bY = bin(u[,2], cutY);           /* bins in Y direction: 1,2,...,ky */
   bin = bX + (ncol(cutX)-1)*(bY-1);      /* assign bins 1,2,...,kx*ky */
   return(bin);
finish;
 
k = 10;                             /* divide vars into deciles  */
prob = (1:k-1)/k;                   /* vector 0.1, 0.2,..., 0.9  */
call qntl(qX, Z[,1], prob);         /* empirical quantiles for X */
call qntl(qY, Z[,2], prob);         /*    ...and Y               */
 
/* divide 2-D data into the k*k bins specified by the quantiles  */
cutX = .M || qX` || .P;
cutY = .M || qY` || .P;
b = bin2D(Z, cutX, cutY);          /* bin numbers 1-k^2*/
 
u = unique(b);                     /* which bins are occupied?   */
means = j(ncol(u), 2, .);          /* allocate matrix for means  */
count = j(ncol(u), 1, .);          /* allocate matrix for counts */
do i = 1 to ncol(u);               /* for each bin:              */
   idx = loc(b = u[i]);            /*   find obs in the i_th bin */
   count[i] = ncol(idx);           /*   how many obs in bin?     */
   means[i,] = mean( Z[idx,] );    /*   mean position within bin */
end;
 
title "Scatter Plot of Mean Values in Each Bin";
call scatter(means[,1], means[,2]) xvalues=qX` yvalues=qY` grid={x y};
quantbinplot1

The scatter plot shows the location of the mean value for each of the 100 bins. For most bins, the markers are not centered in the rectangle, but are offset, which indicates that the distribution of points within the rectangles is not uniform. For example the mean values in the fourth vertical column are all far to the left in their bins.

Sometimes you cannot predict the advantages and disadvantages of a new graph type until you begin using it with real data. For this quantile bin plot, there is one glaring weakness: the graph does not indicate how many observations are in each bin. The next section addresses this weakness.

Improving the quantile bin plot

For these data, the number of points in the bins vary greatly. One bin contains only 184 observations (0.3% of the 50,000 observations) whereas another has 972 observations (1.9%). The median number of observations in a bin is 465. Yet none of that information is available on the graph.

It seems like it would be useful to know how many observations are in each bin. Even if the exact numbers are not needed, it would be nice to know which bins have more observations than others. I propose adding a fourth requirements for the quantile bin plot: a way to visualize the number of points in each bin.

Possible approaches include representing size by using the area of the mean marker. Another would be to overlay the scatter plot on a heat map of the counts. I implemented both of these methods. You can download the SAS program that creates all the graphs in this article.

quantbinplot2

In SAS software, you can use the BUBBLE statement in the SGPLOT procedure to create markers whose areas are proportional to the bin counts. This is shown to the left. (Click to enlarge.) I also used data labels to indicate the exact count. Notice that the area of the smallest bubble (located about halfway across the bottom row) is about five times smaller than the area of the largest bubble (located near the upper right corner). If you have SAS 9.4m2, you can even use the new COLORRESPONSE= and COLORMODEL= options to draw each bubble in a color that reflects its count (not shown).

I think this bubble plot is an improvement over the original design. You can quickly see the bin counts in two ways, which is an advantage. However, this bubble plot makes it harder to determine the mean within each bin, which is a disadvantage. I don't how important the mean positions are to the person who proposed this graph.

quantbinplot3

Another visualization option is to overlay the scatter plot of mean positions on a heat map of the counts in each bin. This is shown to the left. Notice that this graph shows the full range of the data, whereas the range for the scatter plots was determined only by the mean values. This plot indicates that the bin counts are positively correlated. The bins in the upper left and lower right have fewer observations than the bins in the lower left and upper right. The graph also shows that the third, sixth, and ninth vertical strips contain more observations than the other strips. This is because many of the original maternal weights were binned to the nearest 5 pounds. Histograms and other bin plots often show artifacts when applied to data that are themselves binned.

I'd like some feedback on this design. Can you think of an application for this plot? Do you like the design choices I made? Download the SAS program and modify it to plot your own data. Leave a comment to let me know what you think.

tags: Data Analysis, Statistical Graphics



Please comment on the article here: The DO Loop

The post Designing a quantile bin plot appeared first on All About Statistics.

]]>
/2014/09/24/designing-a-quantile-bin-plot/feed/ 0 /2014/09/24/designing-a-quantile-bin-plot/
a weird beamer feature… http://feedproxy.google.com/~r/statsblogs/~3/g_V96J3zHc0/ /2014/09/23/a-weird-beamer-feature/#comments Tue, 23 Sep 2014 22:14:45 +0000 xi'an http://xianblog.wordpress.com/?p=25113 As I was preparing my slides for my third year undergraduate stat course, I got a weird error that got a search on the Web to unravel: which was related with a fragile environment but not directly the verbatim part: the reason for the bug was that the \end{frame} command did not have a line […]

The post a weird beamer feature… appeared first on All About Statistics.

]]>
(This article was originally published at Xi'an's Og » R, and syndicated at StatsBlogs.)

As I was preparing my slides for my third year undergraduate stat course, I got a weird error that got a search on the Web to unravel:

! Extra }, or forgotten \endgroup.
\endframe ->\egroup
  \begingroup \def \@currenvir {frame}
l.23 \end{frame}
  \begin{slide}
?

which was related with a fragile environment

\begin{frame}[fragile]
\frametitle{simulation in practice}
\begin{itemize}
\item For a given distribution $F$, call the corresponding 
pseudo-random generator in an arbitrary computer language
\begin{verbatim}
> x=rnorm(10)
> x
 [1] -0.021573 -1.134735  1.359812 -0.887579
 [7] -0.749418  0.506298  0.835791  0.472144
\end{verbatim}
\item use the sample as a statistician would
\begin{verbatim}
> mean(x)
[1] 0.004892123
> var(x)
[1] 0.8034657
\end{verbatim}
to approximate quantities related with $F$
\end{itemize}
\end{frame}\begin{frame}

but not directly the verbatim part: the reason for the bug was that the \end{frame} command did not have a line by itself! Which is one rare occurrence where the carriage return has an impact in LaTeX, as far as I know… (The same bug appears when there is an indentation at the beginning of the line. Weird!) [Another annoying feature is wordpress turning > into &gt; in the sourcecode environment...]


Filed under: Books, Kids, Linux, R, Statistics, University life Tagged: Beamer, bootstrap, course, fragile environment, LaTeX, R, random number generation, rnorm(), slides, Statistics, Université Paris Dauphine, verbatim, \end{frame}



Please comment on the article here: Xi'an's Og » R

The post a weird beamer feature… appeared first on All About Statistics.

]]>
/2014/09/23/a-weird-beamer-feature/feed/ 0 /2014/09/23/a-weird-beamer-feature/
Factors are not first-class citizens in R http://feedproxy.google.com/~r/statsblogs/~3/5h5d4xis1VU/ /2014/09/23/factors-are-not-first-class-citizens-in-r/#comments Tue, 23 Sep 2014 16:50:25 +0000 John Mount http://www.win-vector.com/blog/?p=2840 The primary user-facing data types in the R statistical computing environment behave as vectors. That is: one dimensional arrays of scalar values that have a nice operational algebra. There are additional types (lists, data frames, matrices, environments, and so-on) but the most common data types are vectors. In fact vectors are so common in R […]

The post Factors are not first-class citizens in R appeared first on All About Statistics.

]]>
(This article was originally published at Win-Vector Blog » Statistics, and syndicated at StatsBlogs.)

The primary user-facing data types in the R statistical computing environment behave as vectors. That is: one dimensional arrays of scalar values that have a nice operational algebra. There are additional types (lists, data frames, matrices, environments, and so-on) but the most common data types are vectors. In fact vectors are so common in R that scalar values such as the number 5 are actually represented as length-1 vectors. We commonly think about working over vectors of “logical”, “integer”, “numeric”, “complex”, “character”, and “factor” types. However, a “factor” is not a R vector. In fact “factor” is not a first-class citizen in R, which can lead to some ugly bugs.

For example, consider the following R code.

levels <- c('a','b','c')
f <- factor(c('c','a','a',NA,'b','a'),levels=levels)
print(f)
## [1] c    a    a    <NA> b    a   
## Levels: a b c
print(class(f))
## [1] "factor"

This example encoding a series of 6 observations into a known set of factor-levels ('a', 'b', and 'c'). As is the case with real data some of the positions might be missing/invalid values such as NA. One of the strengths of R is we have a uniform explicit representation of bad values, so with appropriate domain knowledge we can find and fix such problems. Suppose we knew (by policy or domain experience) that the level 'a' was a suitable default value to use when the actual data is missing/invalid. You would think the following code would be the reasonable way to build a new revised data column.

fRevised <- ifelse(is.na(f),'a',f)
print(fRevised)
##  [1] "3" "1" "1" "a" "2" "1"
print(class(fRevised))
## [1] "character"

Notice the new column fRevised is an absolute mess (and not even of class/type factor). This sort of fix would have worked if f had been a vector of characters or even a vector of integers, but for factors we get gibberish.

We are going to work through some more examples of this problem.

R is designed to support statistical computation. In R analyses and calculations are often centered on a type called a data-frame. A data frame is very much like a SQL table in that it is a sequence of rows (each row representing an instance of data) organized against a column schema. This is also very much like a spreadsheet where we have good column names and column types. (One caveat: in R vectors that are all NA typically lose their type information and become type "logical".) An example of an R data frame is given below.

d <- data.frame(x=c(1,-0.4),y=c('a','b'))
print(d)
##      x y
## 1  1.0 a
## 2 -0.4 b

A R data frame is actually implemented as a list of columns, each column being treated as a vector. This encourages a very powerful programming style where we specify transformations as operations over columns. An example of working over column vectors is given below:

d <- data.frame(x=c(1,-0.4),y=c('a','b'))
d$xSquared <- d$x^2
print(d)
##      x y xSquared
## 1  1.0 a     1.00
## 2 -0.4 b     0.16

Notice that we did not need to specify any for-loop, iteration, or range over the rows. We work over column vectors to great advantage in clarity and speed. This is fairly clever as traditional databases tend to be row-oriented (define operations as traversing rows) and spreadsheets tend to be cell-oriented (define operations over ranges of cells). We can confirm R’s implementation of data frames is in fact a list of column vectors (not merely some other structure behaving as such) through the unclass-trick:

print(class(unclass(d)))
## [1] "list"
print(unclass(d))
## $x
## [1]  1.0 -0.4
## 
## $y
## [1] a b
## Levels: a b
## 
## $xSquared
## [1] 1.00 0.16
## 
## attr(,"row.names")
## [1] 1 2

The data frame d is implemented as a class/type annotation over a list of columns (x, y, and xSquared). Let’s take a closer look at the class or type of the column y.

print(class(d$y))
## [1] "factor"

The class of y is "factor". We gave R a sequence of strings and it promoted or coerced them into a sequence of factor levels. For statistical work this makes a lot of sense; we are more likely to want to work over factors (which we will define soon) than over strings. And at first glance R seems to like factors more than strings. For example summary() works better with factors than with strings:

print(summary(d))
##        x         y        xSquared   
##  Min.   :-0.40   a:1   Min.   :0.16  
##  1st Qu.:-0.05   b:1   1st Qu.:0.37  
##  Median : 0.30         Median :0.58  
##  Mean   : 0.30         Mean   :0.58  
##  3rd Qu.: 0.65         3rd Qu.:0.79  
##  Max.   : 1.00         Max.   :1.00  

print(summary(data.frame(x=c(1,-0.4),y=c('a','b'),
   stringsAsFactors=FALSE)))
##        x              y            
##  Min.   :-0.40   Length:2          
##  1st Qu.:-0.05   Class :character  
##  Median : 0.30   Mode  :character  
##  Mean   : 0.30                     
##  3rd Qu.: 0.65                     
##  Max.   : 1.00   

Notice how if y is a factor column we get nice counts of how often each factor-level occurred, but if y is a character type (forced by setting stringsAsFactors=FALSE to turn off conversion) we don’t get a usable summary. So as a a default behavior R promotes strings/characters to factors and has better summaries for strings/characters than for factors. This would make you think that factors might be a preferred/safe data type in R. This turns out to not completely be the case. A careful R programmer must really decide when and where they want to allow factors in their code.

What is a factor? In principle a factor is a value where the value is known to be taken from a known finite set of possible values called levels. This is similar to an enumerated type. Typically we think of factor levels or categories taking values from a fixed set of strings. Factors are very useful in encoding categorical responses or data. For example we can represent which continent a country is in with the factor levels "Asia", "Africa", "North America", "South America", "Antarctica", "Europe", and "Australia". When the data has been encoded as a factor (perhaps during ETL) you not only have the continents indicated, you also know the complete set of continents and have a guarantee of no ad-hoc alternate responses (such as “SA” for South America). Additional machine-readable knowledge and constraints make downstream code much more compact, powerful, and safe.

You can think of a factor vector as a sequence of strings with an additional annotation as to what universe of strings the strings are taken from. The R implementation of factor actually implements factor as a sequence of integers where each integer represents the index (starting from 1) of the string in the sequence of possible levels.

print(class(unclass(d$y)))
## [1] "integer"
print(unclass(d$y))
## [1] 1 2
## attr(,"levels")
## [1] "a" "b"

This implementation difference should not matter, except R exposes implementation details (more on this later). Exposing implementation details is generally considered to be a bad thing as we don’t know if code that uses factors is using the declared properties and interfaces or is directly manipulating the implementation.

Down-stream users or programmers are supposed to mostly work over the supplied abstraction not over the implementation. Users should not routinely have direct access to the implementation details and certainly not be able to directly manipulate the underlying implementation. In many cases the user must be aware of some of the limitations of the implementation, but this is considered a necessary undesirable consequence of a leaky abstraction. An example of a necessarily leaky abstraction: abstracting base-2 floating point arithmetic as if it were arithmetic over the real numbers. For decent speed you need your numerics to be based on machine floating point (or some multi-precision extension of machine floating point), but you want to think of numerics abstractly as real numbers. With this leaky compromise the user doesn’t have to have the entire IEEE Standard for Floating-Point Arithmetic (IEEE 754) open on their desk at all times. But the user should known the exceptions like: (3-2.9)<=0.1 tends to evaluate to FALSE (due to the implementation, and in violation of the claimed abstraction) and know the necessary defensive coding practices (such as being familiar with What Every Computer Scientist Should Know About Floating-Point Arithmetic).

Now: factors can be efficiently implemented perfectly, so they should be implemented perfectly. At first glance it appears that they have been implemented correctly in R and the user is protected from the irrelevant implementation details. For example if we try and manipulate the underlying integer array representing the factor levels we get caught.

d$y[1] <- 2
## Warning message:
## In `[<-.factor`(`*tmp*`, 1, value = c(NA, 1L)) :
##   invalid factor level, NA generated

This is good, when we tried to monkey with the implementation we got caught. This is how the R implementors try to ensure there is not a lot of user code directly monkeying with the current representation of factors (leaving open the possibility of future bug-fixes and implementation improvements). Likely this safety was gotten by overloading/patching the [<- operator. However, as with most fix-to-finish designs, a few code paths are missed and there are places the user is exposed to the implementation of factors when they expected to be working over the abstraction. Here are a few examples:

f <- factor(c('a','b','a')) # make a factor example
print(class(f))
## [1] "factor"
print(f)
## [1] a b a
## Levels: a b

# c() operator collapses to implementation
print(class(c(f,f))) 
## [1] "integer"
## [1] 1 2 1 1 2 1
print(c(f,f))
## [1] 1 2 1 1 2 1

# ifelse(,,) operator collapses to implementation
print(ifelse(rep(TRUE,length(f)),f,f))
# [1] 1 2 1

# factors are not actually vectors
# this IS as claimed in help(vector)
print(is.vector(f))
## [1] FALSE

# factor implementations are not vectors either
# despite being "integer"
print(class(unclass(f)))
## [1] "integer"
print(is.vector(unclass(f)))
## [1] FALSE

# unlist of a factor is not a vector
# despite help(unlist): 
#   "Given a list structure x, unlist simplifies it to produce a vector:
print(is.vector(unlist(f)))
## [1] FALSE
print(unlist(f))
## [1] a b a
## Levels: a b
print(as.vector(f))
## [1] "a" "b" "a"

What we have done is found instances where a factor column does not behave as we would expect a character vector to behave. These defects in behavior are why I claim factor are not first class in R. They don’t get the full-service expected behavior from a number of basic R operations (such is passing through c() or ifelse(,,) without losing their class label). It is hard to say a factor is treated as a first-class citizens that correctly “supports all the operations generally available to other entities” (quote taken from Wikipedia: First-class_citizen). R doesn’t seem to trust leaving factor data types in factor data types (which should give one pause about doing the same).

The reason these differences are not a mere curiosities is: in any code where we are expecting one behavior and we experience another, we have a bug. So these conversions or abstraction leaks cause system brittleness which can lead to verbose hard to test overly defensive code (see Postel’s law: not sure who to be angry with for some of the downsides of being required to code defensively).


09September 1

September 9, 1947 Grace Murray Hopper “First actual case of bug being found.”

(image: Computer History Museum)

Why should we expect a factor to behave like a character vector? Why not expect it to behave like an integer vector? The reason is: we supplied a character vector and R’s default behavior in data.frame() was to convert it to a factor. R’s behavior only makes sense under the assumption there is some commonality of behavior between factors and character vectors. Otherwise R has made a surprising substitution and violated the principle of least astonishment. To press the point further: from an object oriented view (which is a common way to talk about the separation of concerns of interface and implementation) a valid substitution should at the very least follow some form of the Liskov substitution principle of a factor being a valid sub-type of character vector. But this is not possible between mutable versions of factor and character vector, so the substitution should not have been offered.

What we are trying to point out is: design is not always just a matter of taste. With enough design principles in mind (such as least astonishment, Liskov substitution, and a few others) you can actually say some design decisions are wrong (and maybe even some day some other design decisions are right). There are very few general principals of software system design, so you really don’t want to ignore the few you have.

One possible criticism of my examples is: “You have done everything wrong, everybody knows to set stringsAsFactors=FALSE.” I call this the “Alice’s Adventures in Wonderland” defense. In my opinion the user is a guest and it is fair for the guest to initially assume default settings are generally the correct or desirable settings. The relevant “Alice’s Adventures in Wonderland” quote being:

At this moment the King, who had been for some time busily writing in his note-book, cackled out ‘Silence!’ and read out from his book, ‘Rule Forty-two. All persons more than a mile high to leave the court.’

Everybody looked at Alice.

‘I’m not a mile high,’ said Alice.

‘You are,’ said the King.

‘Nearly two miles high,’ added the Queen.

‘Well, I shan’t go, at any rate,’ said Alice: ‘besides, that’s not a regular rule: you invented it just now.’

‘It’s the oldest rule in the book,’ said the King.

‘Then it ought to be Number One,’ said Alice.


(text: Project Gutenberg)
Queen of Hearts

(image from Wikipedia)

Another obvious criticism is: “You have worked hard to write bugs.” That is not the case, I have worked hard to make consequences direct and obvious. Where I first noticed my bug was code deep in an actual project which is similar to the following example. First let’s build a synthetic data set where y~f(x) where x is a factor or categorical variable.

# build a synthetic data set
set.seed(36236)
n <- 50
d <- data.frame(x=sample(c('a','b','c','d','e'),n,replace=TRUE))
d$train <- FALSE
d$train[sample(1:n,n/2)] <- TRUE
print(summary(d$x))
##  a  b  c  d  e 
##  4  7 12 14 13 

# build noisy = f(x), with f('a')==f('b')
vals <- rnorm(length(levels(d$x)))
vals[2] <- vals[1]
names(vals) <- levels(d$x)
d$y <- rnorm(n) + vals[d$x]
print(vals)
##          a          b          c          d          e 
##  1.3394631  1.3394631  0.3536642  1.6990172 -0.5423986 

# build a model
model1 <- lm(y~0+x,data=subset(d,train))
d$pred1 <- predict(model1,newdata=d)
print(summary(model1))
## 
## Call:
## lm(formula = y ~ 0 + x, data = subset(d, train))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.53459 -0.43303 -0.07942  0.49278  2.20614 
## 
## Coefficients:
##    Estimate Std. Error t value Pr(>|t|)    
## xa   2.9830     0.7470   3.993 0.000715 ***
## xb   2.0506     0.5282   3.882 0.000926 ***
## xc   1.2824     0.3993   3.212 0.004378 ** 
## xd   2.3644     0.3993   5.922  8.6e-06 ***
## xe  -1.1541     0.4724  -2.443 0.023974 *  
## ---
## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
## 
## Residual standard error: 1.056 on 20 degrees of freedom
## Multiple R-squared:  0.8046,	Adjusted R-squared:  0.7558 
## F-statistic: 16.47 on 5 and 20 DF,  p-value: 1.714e-06

Our first model is good. But during the analysis phase we might come across some domain knowledge, such as 'a' and 'b' are actually equivalent codes. We could reduce fitting variance by incorporating this knowledge in our feature engineering. In this example it won’t be much of an improvement, we are not merging much and not eliminating many degrees of freedom. In a real production example this can be a very important step where you may have a domain supplied roll-up dictionary that merges a large number of levels. However, what happens is our new merged column gets quietly converted to a column of integers which is then treated as a numeric column in the following modeling step. So the merge is in fact disastrous, we lose the categorical structure of the variable. We can, of course, re-institute the structure by calling as.factor() if we know about the problem (which we might not), but even then we have lost the string labels for new integer level labels (making debugging even harder). Let’s see the failure we are anticipating, notice how the training adjusted R-squared disastrously drops from 0.7558 to 0.1417 after we attempt our “improvement.”

# try (and fail) to build an improved model
# using domain knowledge f('a')==f('b')
d$xMerged <- ifelse(d$x=='b',factor('a',levels=levels(d$x)),d$x)
print(summary(as.factor(d$xMerged))) 
##  1  3  4  5 
## 11 12 14 13 

# disaster! xMerged is now class integer 
# which is treated as numeric in lm, losing a lot of information
model2 <- lm(y~0+xMerged,data=subset(d,train))
print(summary(model2))
## 
## Call:
## lm(formula = y ~ 0 + xMerged, data = subset(d, train))
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.3193 -0.5818  0.8281  1.6237  3.5451 
## 
## Coefficients:
##         Estimate Std. Error t value Pr(>|t|)  
## xMerged   0.2564     0.1132   2.264   0.0329 *
## ---
## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
## 
## Residual standard error: 1.98 on 24 degrees of freedom
## Multiple R-squared:  0.176,	Adjusted R-squared:  0.1417 
## F-statistic: 5.128 on 1 and 24 DF,  p-value: 0.03286

There is an obvious method to merge the levels correctly: convert back to character (which we show below). The issue is: if you don’t know about the conversion to integer happening, you may not know to look for it and correct it.

# correct f('a')==f('b') merge
d$xMerged <- ifelse(d$x=='b','a',as.character(d$x))
model3 <- lm(y~0+xMerged,data=subset(d,train))
d$pred3 <- predict(model3,newdata=d)
print(summary(model3))
## 
## Call:
## lm(formula = y ~ 0 + xMerged, data = subset(d, train))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -2.53459 -0.51084 -0.05408  0.71385  2.20614 
## 
## Coefficients:
##          Estimate Std. Error t value Pr(>|t|)    
## xMergeda   2.3614     0.4317   5.470 1.99e-05 ***
## xMergedc   1.2824     0.3996   3.209  0.00422 ** 
## xMergedd   2.3644     0.3996   5.916 7.15e-06 ***
## xMergede  -1.1541     0.4729  -2.441  0.02361 *  
## ---
## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
## 
## Residual standard error: 1.057 on 21 degrees of freedom
## Multiple R-squared:  0.7945,	Adjusted R-squared:  0.7553 
## F-statistic:  20.3 on 4 and 21 DF,  p-value: 5.693e-07

dTest <- subset(d,!train)
nTest <- dim(dTest)[[1]]

# Root Mean Square Error of original model on test data
print(sqrt(sum((dTest$y-dTest$pred1)^2)/nTest))
## [1] 1.330894

# Root Mean Square Error of f('a')==f('b') model on test data
print(sqrt(sum((dTest$y-dTest$pred3)^2)/nTest))
## [1] 1.297682

Factors are definitely useful, and I am glad R has them. I just wish they had fewer odd behaviors. My rule of thumb is just to use them as late as possible, set stringsAsFactors=FALSE and if you need factors in some place convert from character near that place.

Please see the following articles for more ideas on working with categorical variables and preparing data for analysis.



Please comment on the article here: Win-Vector Blog » Statistics

The post Factors are not first-class citizens in R appeared first on All About Statistics.

]]>
/2014/09/23/factors-are-not-first-class-citizens-in-r/feed/ 0 /2014/09/23/factors-are-not-first-class-citizens-in-r/
Why I’m still not persuaded by the claim that subliminal smiley-faces can have big effects on political attitudes http://feedproxy.google.com/~r/statsblogs/~3/rcHb1c1GUFQ/ /2014/09/23/why-im-still-not-persuaded-by-the-claim-that-subliminal-smiley-faces-can-have-big-effects-on-political-attitudes/#comments Tue, 23 Sep 2014 13:35:19 +0000 Andrew http://andrewgelman.com/?p=23682

We had a discussion last month on the sister blog regarding the effects of subliminal messages on political attitudes.  It started with a Larry Bartels post entitled “Here’s how a cartoon smiley face punched a big hole in democratic theory,” with the subtitle, “Fleeting exposure to ‘irrelevant stimuli’ powerfully shapes our assessments of policy arguments,” discussing the […]

The post Why I’m still not persuaded by the claim that subliminal smiley-faces can have big effects on political attitudes appeared first on Statistical Modeling, Causal Inference, and Social Science.

The post Why I’m still not persuaded by the claim that subliminal smiley-faces can have big effects on political attitudes appeared first on All About Statistics.

]]>
(This article was originally published at Statistical Modeling, Causal Inference, and Social Science, and syndicated at StatsBlogs.)

We had a discussion last month on the sister blog regarding the effects of subliminal messages on political attitudes.  It started with a Larry Bartels post entitled “Here’s how a cartoon smiley face punched a big hole in democratic theory,” with the subtitle, “Fleeting exposure to ‘irrelevant stimuli’ powerfully shapes our assessments of policy arguments,” discussing the results of an experiment conducted a few years ago and recently published by Cengiz Erisen, Milton Lodge and Charles Taber. Larry wrote:

What were these powerful “irrelevant stimuli” that were outweighing the impact of subjects’ prior policy views? Before seeing each policy statement, each subject was subliminally exposed (for 39 milliseconds — well below the threshold of conscious awareness) to one of three images: a smiling cartoon face, a frowning cartoon face, or a neutral cartoon face. . . . the subliminal cartoon faces substantially altered their assessments of the policy statements . . .

I followed up with a post expressing some skepticism:

It’s clear that when the students [the participants in the experiment] were exposed to positive priming, they expressed more positive thoughts . . . But I don’t see how they make the leap to their next statement, that these cartoon faces “significantly and consistently altered [students'] thoughts and considerations on a political issue.” I don’t see a change in the number of positive and negative expressions as equivalent to a change in political attitudes or considerations.

I wrote:

Unfortunately they don’t give the data or any clear summary of the data from experiment No. 2, so I can’t evaluate it. I respect Larry Bartels, and I see that he characterized the results as the “subliminal cartoon faces substantially altered their assessments of the policy statements — and the resulting negative and positive thoughts produced substantial changes in policy attitudes.” But based on the evidence given in the paper, I can’t evaluate this claim.  I’m not saying it’s wrong. I’m just saying that I can’t express judgment on it, given the information provided.

Larry then followed up with a post saying that further information was in chapter 3 of Erison’s Ph.D. dissertation, available online here.

And Erisen sent along a note which I said I would post. Erisen’s note is here:

As a close follower of the Monkey Cage, it is a pleasure to see some interest in affect, unconscious stimuli, perceived (or registered) but unappreciated influences. Accordingly I thought it is now the right time for me to contribute to the discussion.

First, I would like to begin with clarifying conceptual issues with respect to affective priming. Affective priming is not subliminal advertising, nor is it a subliminal message. Subliminal ads (or messages) were used back in the 1970s with questionable methods and current priming studies rarely refer to these approaches.

Second, it is quite normal to be skeptical because no earlier research has attempted to address these kinds of issues in political science. When they first hear about affective influences, people may naturally consider the consequences for measuring political attitudes and political preferences. These conclusions may be especially meaningful for democratic theory, as mentioned by Larry Bartels in an earlier post.

But, fear not, this is not a stand-alone research study. Rather, it is part of an overall research program (Lodge and Taber, 2013) and there are various studies on unconscious stimuli and contextual effects. We name these “perceived but unappreciated effects” in our paper. In addition, we cite some other work on contextual cues (Berger et al., 2008), facial attractiveness (Todorov and Uleman, 2004), the “RATS” ad (Weinberger and Westen, 2008), the Willie Horton ad (Mendelberg, 2001), upbeat music or threatening images in political ads (Brader, 2006), which all provide examples of priming. There is a great deal of research in social psychology that offers other relevant examples of the social or political effects of affective primes.

Third, with respect to the outcomes, I would like to refer the reader to our path analyses (provided in the paper and in The Rationalizing Voter) that show the effects of affect-triggered thoughts on policy preferences (see below). What can be inferred from these results? We can say that controlling for prior attitudes affective primes not only directly affected policy preferences but also indirectly affected preferences through affect-evoked thoughts. The effects on political attitudes and preferences are significant as we discuss in greater detail in the paper.

erisen

Fourth, these results were consistent across six experiments that I conducted for my dissertation. Priming procedure was about the same in all those studies and patterns across different dependent variables were quite similar.

Finally, we do not argue that voters cannot make decisions based on “enlightened preferences.” As we repeatedly state in the paper, affective cues color attitudes and preferences but this does not mean that voters’ decisions are necessarily irrational.

Both Bartels and Erisen posted path diagrams in support of their argument, so perhaps I should clarify that I’ve never understood these path diagrams. If an intervention has an effect on political attitudes, I’d like to see a comparison of the political attitudes with and without the intervention.  No amount of path diagrams will convince me until I see the direct comparison. You could argue with some justification that my ignorance in this area is unfortunate, but you should also realize that there are a lot of people like me who don’t understand those graphs—and I suspect that many of those people who do like and understand path diagrams would also like to see the direct comparisons too.  So, purely from the perspective of communication, I think it makes sense to connect the dots and not just show a big model without the intermediate steps.  Otherwise you’re essentially asking the reader to take your claims on faith.

Again, I’m not saying that Erisen is wrong in his claims, just that the evidence he’s shown me is too abstract to convince me.   I realize that he knows a lot more about his experiment and his data than I do and I’m pretty sure that he is much more informed on this literature than I am, so I respect that he feels he can draw certain strong conclusions from his data.  But, for me, I have to go what information is available to me.

P.S.  In his post, Larry also refers to the study of  Andrew Healy, Neil Malhotra, and Cecilia Hyunjung Mo on college football games and election outcomes.  That was an interesting study but, as I wrote when it came out a couple years ago, I think its implications were much less than were claimed at the time in media reports.  Yes, people can be affected by irrelevant stimuli related to mood, but it matters what are the magnitudes of such effects.

The post Why I’m still not persuaded by the claim that subliminal smiley-faces can have big effects on political attitudes appeared first on Statistical Modeling, Causal Inference, and Social Science.



Please comment on the article here: Statistical Modeling, Causal Inference, and Social Science

The post Why I’m still not persuaded by the claim that subliminal smiley-faces can have big effects on political attitudes appeared first on All About Statistics.

]]>
/2014/09/23/why-im-still-not-persuaded-by-the-claim-that-subliminal-smiley-faces-can-have-big-effects-on-political-attitudes/feed/ 0 /2014/09/23/why-im-still-not-persuaded-by-the-claim-that-subliminal-smiley-faces-can-have-big-effects-on-political-attitudes/
Managing R package dependencies http://feedproxy.google.com/~r/statsblogs/~3/XkJB3YcUw_I/ /2014/09/23/managing-r-package-dependencies/#comments Tue, 23 Sep 2014 06:47:00 +0000 Markus Gesmann /?guid=800c0a97cd623382efa7fd3ccaffb5cc One of my take aways from last week's EARL conference was that R is more and more growing out of its academic roots into the enterprise. And with that come some challenges, e.g. how do I ensure consistent and systematic access to a set of R packages in...

The post Managing R package dependencies appeared first on All About Statistics.

]]>
(This article was originally published at mages' blog, and syndicated at StatsBlogs.)

One of my take aways from last week's EARL conference was that R is more and more growing out of its academic roots into the enterprise. And with that come some challenges, e.g. how do I ensure consistent and systematic access to a set of R packages in an organisation, in particular when one team is providing packages to others?

Two packages can help here: roxyPackage and miniCRAN.

I wrote about roxyPackage earlier on this blog. It allows me to create a local repository to distribute my package, while at the same time execute and control the build process from within R. But what about my package's dependencies? Here miniCRAN helps. miniCRAN is a new package by Andrie de Vries that enables me to find and download all package dependencies and store them in a local repository, e.g. the one used by roxyPackage.

For more details about roxyPackage and miniCRAN read the respective package vignettes.

Example

To create a local sub-CRAN repository for the two packages I maintain on CRAN and with all their dependencies I use:
library("miniCRAN")
my.pkgs <- c("googleVis", "ChainLadder")
pkgs <- pkgDep(my.pkgs, suggests = TRUE, enhances=FALSE)
makeRepo(pkgs = pkgs, path="/Users/Shared/myCRANRepos")
And to visualise the dependencies:
dg <- makeDepGraph(my.pkgs, includeBasePkgs=FALSE, 
suggests=TRUE, enhances=TRUE)
set.seed(1)
plot(dg, legendPosEdge = c(-1, 1),
legendPosVertex = c(1, 1), vertex.size=20)

What a surprise! In total I end up with 42 packages from CRAN and I didn't expect any connection between the ChainLadder and googleVis package.

Bonus tip

Don't miss out on Pat Burns's insightful talk about effective risk management from EARL. His thoughts reminded me of the great Karl Popper: Good tests kill flawed theories; we remain alive to guess again.

Session Info

R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base

other attached packages:
[1] miniCRAN_0.1-0

loaded via a namespace (and not attached):
[1] httr_0.5 igraph_0.7.1 stringr_0.6.2 tools_3.1.1
[5] XML_3.98-1.1



Please comment on the article here: mages' blog

The post Managing R package dependencies appeared first on All About Statistics.

]]>
/2014/09/23/managing-r-package-dependencies/feed/ 0 /2014/09/23/managing-r-package-dependencies/