GPT today: Buffon’s Needle in Python with plotting (and some jokes)

Werner Krauth is visiting NYU’s Simons Center for Physics from ENS in Paris. He’s a physicist and the author of the 2006 book Statistical Mechanics: Algorithms and Computations. And he’s stopping by our reading group Fridays, where I learned about his most peculiar approach to plotting. He coded it in Postscript (!!! see below) and ran simulations on the printer. The result is quite beautiful. Here’s Figure 1.10 from the text.


Buffon's needles, by Werner Krauth, copyright 2006

I wondered how well GPT would do at this task. It’s pretty complicated, but then Buffon’s well represented on the internet. Let’s give it a shot. Here’s my prompt:

BC: From a book on molecular dynamics, “We want to follow in Count Buffon’s footsteps and and perform our own needle-throwing experiments. One of these, with 2000 samples, is shown in Fig. 1.10.” Write a Python program to generate those 2000 samples. Then take the 2000 samples and write code to plot them. Each needle should be displayed as a line connected to a needle eye with a small ball in the middle. There should be 17 “cracks” in the experiment and the ball should be solid if a needle overlaps a crack. The field overall is sized 20 high x 16 wide and has 17 vertical cracks. Each needle is unit length.

At which point, GPT gave me three blocks of code (see below), and when I ran it, this was the result.


Buffon's needles by ChatGPT4 May 23, 2024 (version 1)

This is actually better than I expected. You can see it got the distinction right of white circles versus red circles, but not quite the right visualization. So I asked it to try again with this prompt:

BC: That’s great, but there are several improvements I’d like to see.

1. Black and white rendering only.
2. Thinner lines and smaller circles and disks.
3. Plot the vertical cracks with thin lines.
4. Put a needle like shape (like an American football) on one end of each needle to give it an orientation.

I just need the final Plotting the Needles code for this.

Et voila.


Buffon's needles by ChatGPT May 23, 2024 (version 2)

Well, almost. It forgot to distinguish the ones that overlapped with circles rather than black disks.

This took a total of 2 minutes (plus 10 minutes to get into the blog, because it’s totally manual).

Here’s the code snippets it produced.

import numpy as np

def generate_needles(num_samples, field_width, field_height):
    # Generate random midpoints
    x = np.random.uniform(0, field_width, num_samples)
    y = np.random.uniform(0, field_height, num_samples)
    # Generate random angles from 0 to 2*pi
    theta = np.random.uniform(0, 2*np.pi, num_samples)
    
    return x, y, theta

# Constants
num_samples = 2000
field_width = 16
field_height = 20

x, y, theta = generate_needles(num_samples, field_width, field_height)

def check_overlaps(x, y, theta, field_width, num_cracks):
    crack_positions = np.linspace(0, field_width, num_cracks + 1)
    overlaps = np.zeros(len(x), dtype=bool)
    
    for i in range(len(x)):
        # Calculate endpoints
        x1 = x[i] + 0.5 * np.cos(theta[i])
        y1 = y[i] + 0.5 * np.sin(theta[i])
        x2 = x[i] - 0.5 * np.cos(theta[i])
        y2 = y[i] - 0.5 * np.sin(theta[i])
        
        # Check for overlap
        min_x = min(x1, x2)
        max_x = max(x1, x2)
        overlaps[i] = np.any((crack_positions > min_x) & (crack_positions < max_x))
        
    return overlaps

overlaps = check_overlaps(x, y, theta, field_width, 17)

import matplotlib.pyplot as plt

def plot_needles(x, y, theta, overlaps):
    fig, ax = plt.subplots(figsize=(8, 6))
    for i in range(len(x)):
        # Endpoints
        x1 = x[i] + 0.5 * np.cos(theta[i])
        y1 = y[i] + 0.5 * np.sin(theta[i])
        x2 = x[i] - 0.5 * np.cos(theta[i])
        y2 = y[i] - 0.5 * np.sin(theta[i])
        
        # Plot needle
        ax.plot([x1, x2], [y1, y2], 'k-')
        # Plot needle eye
        ax.plot(x[i], y[i], 'ro' if overlaps[i] else 'wo')
    
    ax.set_xlim(0, field_width)
    ax.set_ylim(0, field_height)
    ax.set_aspect('equal')
    plt.show()

plot_needles(x, y, theta, overlaps)

This is very neat and well organized code! Here's the followup code.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def plot_needles(x, y, theta, overlaps):
    fig, ax = plt.subplots(figsize=(8, 6))
    
    # Plot vertical cracks
    field_width = 16
    num_cracks = 17
    crack_positions = np.linspace(0, field_width, num_cracks + 1)
    for cp in crack_positions:
        ax.axvline(x=cp, color='gray', linestyle='-', linewidth=0.5)
    
    # Settings for needles and circles
    line_width = 0.5
    circle_radius = 0.05  # radius for midpoint marker
    needle_length = 1
    football_length = 0.2  # length of the "football" shape
    
    for i in range(len(x)):
        # Calculate endpoints
        x1 = x[i] + 0.5 * np.cos(theta[i])
        y1 = y[i] + 0.5 * np.sin(theta[i])
        x2 = x[i] - 0.5 * np.cos(theta[i])
        y2 = y[i] - 0.5 * np.sin(theta[i])
        
        # Draw needle
        ax.plot([x1, x2], [y1, y2], 'k-', lw=line_width)
        
        # Draw "American football" shape
        football_x = x[i] + 0.5 * np.cos(theta[i]) - football_length * np.cos(theta[i])
        football_y = y[i] + 0.5 * np.sin(theta[i]) - football_length * np.sin(theta[i])
        ellipse = patches.Ellipse((football_x, football_y), football_length, circle_radius, 
                                  angle=np.degrees(theta[i]), color='black')
        ax.add_patch(ellipse)
        
        # Draw needle eye
        color = 'black' if overlaps[i] else 'white'
        ax.plot(x[i], y[i], marker='o', markersize=circle_radius*30, markeredgecolor='black', markerfacecolor=color)
    
    ax.set_xlim(0, field_width)
    ax.set_ylim(0, field_height)
    ax.set_aspect('equal')
    ax.axis('off')  # Turn off the axis
    plt.show()

plot_needles(x, y, theta, overlaps)

What's really amazing here is that it recognizes "American football shape" and can convert that into Matplotlib code.

Getting better at humor

GPT's getting funnier. This is from Mitzi.

MM: please give me a joke with the punchline "all your base are belong to us"

GPT4: Why did the computer take over the entire internet?

Because it finally decoded the message: "All your base are belong to us."

Thank you sir, may I have another?

MM: that's pretty good. please give me another one.

ChatGPT: Why did the grammar teacher fail the evil overlord's essay?

Because it ended with "All your base are belong to us."

A good comic has a lot of material.

MM: another one?

GPT: Why did the spaceship's navigation system malfunction?

Because the aliens reprogrammed it to say, "All your base are belong to us."

And because it's that time of year.

MM: please make a baseball joke about this

GPT: Why did the opposing baseball team start panicking in the middle of the game?

Because the scoreboard flashed a message: "All your base are belong to us."

Mitzi says "home team" would have been funnier.

The Postscript postscript

Werner shared his postscript code for generating his plot. It runs as part of the postscript rendering. The relevant part is at the bottom starting at "4000".

%!PS-Adobe-2.0 EPSF-2.0
%%Title: IN_buffon_exp_new.eps
%%BoundingBox: 45 131 430 625
%%  Postscript figure from 
%   Statistical Mechanics: Algorithms and Computations
%                   Werner Krauth
%            Oxford University Press (2006)
%
/cm { 0.0351 div} def
/thicklinewidth 1.5 def
/normallinewidth 1.0 def    % 0.35377 mm or 1/72 inch 
/thinlinewidth 0.5 def
/white 1.0 def     %    0 % gray = white
/black .0 def      %   100% gray= black
/tinyradius 0.03 cm  def  %  
                           %
/dot {  % usage: x y radius dot (draws a dot (filled circle) of given radius in current grayvalue)
gsave
   0 360 arc
   gsave
      fill
   grestore
   gsave
      black setgray
      stroke
   grestore
grestore
} def
/circle {  % usage: x y radius circle (draws an unfilled circle of given radius)
           % the linewidth is not specified
gsave
   0 360 arc
   black setgray
   stroke
grestore
} def
/nran {    % usage: N nran (picks random number between 1 and N)
rand exch mod 1 add } def 
/ran01 {    % usage ran01  (picks random number between 0 and 1)
/xnorm 10000 def
rand xnorm mod cvr xnorm div } def 
%%%%%
%%%%% end common area of all Smac postscript figures.
%%%%%
/sc {0.75 mul} def
100 srand
/needle { % usage: angle x y needle, draws a needle, which for angle = 0 extends from
   % -0.5 sc cm to + 0.5 sc cm
   % allows different gray values. Version 04-JUN-03
   gsave
      translate
      rotate
      /l 0.7 sc cm def % factor setting lateral size of hole
      /x .2 sc cm def % 2 x: length of hole
      /y .6 sc cm def % length of shaft
      /radius l dup mul x dup mul add sqrt def
      /alpha x l atan def
%
% make the shaft
%
      thinlinewidth setlinewidth
      1 setlinejoin
      1 setlinecap
      gsave
         y 2 div x -1 mul add 0 translate
         y -1 mul 0 cm moveto
         0 sc cm 0 cm lineto
         gsave
            black setgray
            stroke
         grestore
%
% make the hole
%
         newpath
         x l -1 mul radius 90 alpha add 90 alpha sub arcn
         x l radius 270 alpha add 270 alpha sub arcn
% fill
         gsave
            black setgray
            stroke
         grestore
      grestore
      0 0 tinyradius 1.3 mul dot
   grestore
} def
2 cm 5 cm translate
/ymax 22 sc cm def
/xmax 18. cm def
/delx 1. sc cm def
/ncracks 18 def

thinlinewidth setlinewidth
gsave
200  thinlinewidth setlinewidth
   ncracks {0 sc cm -.5 sc cm moveto 0 sc cm ymax .5 sc cm add lineto stroke delx 0 translate} repeat
   stroke
grestore
white setgray
thinlinewidth setlinewidth
4000 {
   /angle {360 nran} def
   /xcenter {delx .5 mul ran01 mul} def
   /ycenter {ymax ran01 mul} def
   /xc xcenter def
   /an angle def
   xc an cos .5 sc cm mul abs sub 0 lt {black setgray}{white setgray} ifelse
   2 nran 1 gt {/xc delx xc sub def } if
   /xc xc ncracks 1 sub nran 1 sub delx mul add def
   an xc ycenter needle
} repeat
showpage

New stat podcast just dropped

Alexandre Andorra interviewed me for his Learning Bayesian Statistics podcast. The topic was my new book with Aki, Active Statistics: Stories, Games, Problems, and Hands-on Demonstrations for Applied Regression and Causal Inference. In the podcast, Alexandre and I discussed the Two Truths and a Lie activity and many other things.

This actually isn’t the first podcast I’ve recorded with Alexandre. In 2020 he interviewed Jennifer, Aki, and me to talk about our book, Regression and Other Stories, and he also interviewed Merlin and me to talk about our Economist election model.

If you want to see a few more podcasts and a bunch of videos of my recorded presentations, here they are. I guess you can play them at 4x speed and watch them while washing the dishes or whatever. They may not be entertaining but I hope they are informative.

P.S. Alexandre also interviewed Aki all on his own on the topic of model assessment and nonparametric models. Actually . . . hey! Here’s an entire page of videos featuring Aki! For example, here’s a short one on how many digits to report and how many iterations to run for MCMC. Good stuff. Aki uses slides in his presentations, which some of you might appreciate.

“You want to gather data to determine which of two students is a better basketball shooter. You plan to have each student take N shots and then compare their shooting percentages. Roughly how large does N have to be for you to have a good chance of distinguishing a 30% shooter from a 40% shooter?”

Elden Griggs writes:

I have been grading a homework problem where the students have come to two different conclusions. The question was:

You want to gather data to determine which of two students is a better basketball shooter. You plan to have each student take N shots and then compare their shooting percentages. Roughly how large does N have to be for you to have a good chance of distinguishing a 30% shooter from a 40% shooter?

Essentially, there were two sets of student answers. The first set simulated and found the answer to be around 120-130 depending how they rounded (generally they wanted to see whether the stronger shooter won 95% of the time—though some students added some nuance and checked other proportions of winning). The other set of students went about using power analysis from notes further along in the book or their own knowledge and came to the exact answer of N = 354. Here is code from one of the students:

Based on the simulations, I know the answer for the power analysis is pretty conservative (see attached graphic showing the difference between the two n values). My question I guess is why is the power analysis so off?

My reply was this recommended approach:

1. Start with a guess, for example N = 100.

2. If N = 100, then the estimated difference has standard error approximately sqrt(0.5^2/100 + 0.5^2/100) = 0.07.

3. So, if the true difference in probabilities is 0.10, that’s 1.4 standard errors from zero, so the probability that the 40% shooter does better in the actual experiment is pnorm(1.4) = 0.92. With N = 100, there’s a 92% chance that the good shooter wins. 92% seems like more than “a good chance,” so I’d say that N = 100 is just fine.

4. We could try a lower N. For example, if N = 50, then the estimated difference has a s.e. of approx 0.10. Then a true difference of 0.10 is 1.0 s.e.’s from 0, and the probability that the 40% shooter does better in the actual experiment is then pnorm(1.0) = 0.84. 84% is “a good chance” too, I’d say. So, by that measure, N = 50 would be just fine.

5. If you wanted a 95% chance, you can work that out . . . qnorm(0.95) is 1.64, so if the true value is 1.64 s.e.’s from 0, there’s a 95% chance that the experiment will identify the winner. When N = 100, the true value is 1.4 s.e.’s from 0, so to get this to 1.64 s.e.’s from 0, you need to up the sample size by a factor of (1.64/1.4)^2, i.e. you will need a sample size of 100*(1.64/1.4)^2 = 137.

6. Buuuuut . . . I don’t think we need 95%, as the homework just asked for “a good chance.”

7. On the other hand, what does it mean to “distinguish” the two shooters? Maybe it implies that the estimated difference in their abilities should exceed some threshold? One possible rule is that the difference should be “statistically significant” at the 95% level. A conventional criterion is that there be at least an 80% probability that the experiment is successful in the sense of yielding a “95% statistically significant” result. For that, the true difference must be at least 2.8 standard errors from 0, for reasons explained in chapter 16 of Regression and Other Stories. We already know that when N = 100, the true value is 1.4 s.e.’s from 0, so to get to 2.8, you need to up the sample size to 100*(2.8/1.4)^2 = 400.

8. Given the numbers in the problem, we could replace sqrt(0.5^2/100 + 0.5^2/100) by sqrt(0.3*0.7/100 + 0.4*0.6/100) in step 2 above (and changing the later steps accordingly). This is a minor thing, though, and for reasons of general practice I’d recommend using the 0.5’s unless the probabilities are really far from 1/2.

So there are lots of reasonable answers. N=100 would be fine, N=50 would be fine, N=137 would be fine, N=400 would be fine, etc. The key is for them to have reached their results following a series of understandable steps, not just using a formula. The problem with the formula is that it doesn’t generalize to harder problems. The steps above generalize better.

P.S. The above is not supposed to represent any sort of realistic analysis of basketball! For example, I’m ignoring time trends in any hypothetical data and abilities. It’s just a homework problem. The point is to clear up a point that confused some students, and which I’m sure confuses many practitioners as well.

Boris and Natasha in America: How often is the wife taller than the husband?

Shane Frederick, who sometimes sends me probability puzzles, sent along this question:

Among married couples, what’s your best guess about how often the wife is taller than the husband?
• 1 in 10
• 1 in 40
• 1 in 300
• 1 in 5000

I didn’t want to cheat so I tried to think about this one without doing any calculations or looking anything up. My two sources of information were my recollection of the distributions of women’s and men’s heights (this is in Regression and Other Stories) and whatever I could dredge up from my personal experiences with friends and couples I see walking on the street.

I responded to Shane as follows:

I’m embarrassed to say I don’t know the answer to this question of yours. I’d guess 1 in 10, but I guess that 1 in 40 is not entirely out of the question, given that the two heights are positively correlated. So maybe I’d guess 1 in 40. But 1 in 10 is not out of the question…

Shane responded:

It’s roughly 1 in 40 if you assumed non assortative mating (just randomly picked men and women from the respective height distribution of men and women).

In reality, it is closer to 1 in 300. (Women don’t like shorter men; men may not like taller women, and shorter men don’t marry as often, in part because they earn less.)

1 in 300 didn’t sound right to me. So I did some calculating and some looking up.

First the calculating.

compare_heights <- function(mu, sigma, rho, n=1e6){
  Sigma <- diag(sigma) %*% cbind(c(1,rho), c(rho, 1)) %*% diag(sigma)
  library("MASS")
  heights <- mvrnorm(n, mu, Sigma)
  p_wife_taller <- mean(heights[,1] > heights[,2])
  cat("Assuming corr is", rho, ":  probability the wife is taller is", p_wife_taller, ":  1 in", 1/p_wife_taller, "\n")
}
mu <- c(63.7, 69.1)
sigma <- c(2.4, 2.9)
options(digits=2)
for (rho in c(0, 0.3, 0.5, 0.7)){
  compare_heights(mu, sigma, rho)
}

And here's the output:

Assuming corr is 0 :  probability the wife is taller is 0.076 :  1 in 13 
Assuming corr is 0.3 :  probability the wife is taller is 0.044 :  1 in 23 
Assuming corr is 0.5 :  probability the wife is taller is 0.022 :  1 in 45 
Assuming corr is 0.7 :  probability the wife is taller is 0.0052 :  1 in 191 

Using simulation here is overkill---given that we're assuming the normal distribution anyway, it would be easy enough to just compute the probability analytically using the distribution of the difference between husband's and wife's heights (from the numbers above, the mean is 69.1 - 63.7 and the sd is sqrt(2.4^2 + 2.9^2 - 2*rho*2.4*2.9), so for example if rho = 0.5 you can just compute pnorm(0, 69.1 - 63.7, sqrt(2.4^2 + 2.9^2 - 2*0.5*2.4*2.9)), which indeed comes to 0.22.)---but brute force seems safer. Indeed, I originally did the simulation with n=1e4 but then I upped the draws to a million just to be on the safe side, since it runs so fast anyway.

A correlation of about 0.5 sounds right to me, so the above calculations seems to be consistent with my original intuition that the probability would be about 1 in 10 if independent or 1 in 40 accounting for correlation.

Next, the looking up. I recalled that sociologist Philip Cohen had posted something on the topic, so I did some googling and found this press release:

The average height difference between men and women in the U.S is about 6 inches. . . . Cohen also analyzed the height of 4,600 married couples from the 2009 Panel Study of Income Dynamics and found that the average husband's height was 5'11" while the average wife was 5'5". Moreover, he found that only 3.8 percent of the couples were made up of a tall wife and a short husband . . .

Fiona Macrae and Damien Gayle of the Daily Mail picked up this story and compared it to similar research on couples in the U.K, where they found that for most couples - 92.5 percent - the man was taller.

Hmmm . . . 5'5" and 5'11" are taller than the numbers that I'd been using . . . perhaps the people in the PSID were wearing socks?

I also found this post from Cohen based on data from the 2017 wave of the PSID. He supplies these graphs:

There's something weird about these graphs---if heights are given to the nearest inch, they should be presented as histograms, no?---but I think we can read off the percentages.

If you round to the nearest inch, it appears that there is a 4% chance that the two members of the couple have the same height, a 3% chance that the wife is taller, and a 93% chance the husband is taller. So for discrete heights, the probability the wife is taller is approximately 1 in 30. If you allow continuous heights and you allocate a bit less than half the ties to the "wife taller than husband" category, then the probability becomes something like 1 in 25.

Given all this, I wondered how Shane could ever had thought the frequency was 1 in 300. He replied that he got his data from this paper, "The male-taller norm in mate selection," published in Personality and Psychology Bulletin in 1980, which reports this:

Just as an aside, I find it a bit creepy when researchers use the term "mate" when referring to married couples. Wouldn't "spouse" be more appropriate? "Mate" has this anthropological, scientistic feel to it.

To return to the substance, there are two mysteries here. First, how did they calculate that the probability of the woman being taller should be only 2%? Second, how is it that only 1 of 720 of their couples had the wife taller than the husband?

The answer to the first question is supplied by this table from the 1980 paper:

Their standard deviations (2.3" within each sex) are too low. That sort of thing can happen when you try to estimate a distribution using a small and nonrepresentative sample. They continued by assuming a correlation of 0.2 between wives' and husbands' heights. I think 0.2 is too small a correlation, but when you combine it with the means and standard deviations that they assumed, you end up getting something reasonable.

As to the second question . . . I don't know! Here's what they say about their data:

My best guess is that people did some creative rounding to avoid the husband's recorded height being lower than the wife's, but it's hard to know. I don't fault the authors of that paper from 1980 for using whatever data they could find; in retrospect, though, it seems they were doing lots of out-of-control theorizing based on noisy and biased data.

I did some more googling and found this paper from 2014 with more from the Panel Study of Income Dynamics. The authors write:

Height was first measured in the PSID in 1986 and then at every wave starting in
1999. . . . In 1986, 92.7% of men were taller than their spouses; in 2009, 92.2% were taller.

They break the data up into couples where the husbands is shorter than the wife and couples where they are the same height. In 1986, 3.14% of husbands were shorter and 4.13% were the same height. In 2009, 3.78% were shorter and 4.00% were the same height. From these data, if you include something less than half of the "same height" group, you'll get an estimate of approximately 5%, or 1 in 20, couples where the wife is taller than the husband.

So, yeah, between 1 in 10 and 1 in 40. Not 1 in 300.

To be fair to Shane on this one, this was just an example he used in one of his classes. It's an interesting example how it's easy to get confused if you just look at one source, reminiscent of some examples we've discussed earlier in this space:

- What is Russia's GDP per capita?

- The contradictory literature on the effects on political attitudes of having a son or daughter.

- Various claims about the relation between age and happiness.

All these examples feature contradictory claims in the literature that are each made very strongly. The problem is not so much in the disagreement---there is legitimate uncertainty on these issues, along with real variation---but rather that the separate claims are presented as deterministic numbers or as near-certain conclusions. Kinda like this notorious story from Hynes and Vanmarcke (1977) and retold in Active Statistics:

Shane summarizes:

The general message has become even more cynical; transmogrifying from “You can’t trust everything you read,” to “You can’t trust anything you read.”

I wouldn't quite put it that strongly; rather, I'd say that it's a good idea to find multiple data sources and multiple analyses, and don't expect that the first thing you find will tell the whole story.

Simulation to understand two kinds of measurement error in regression

This is all super-simple; still, it might be useful. In class today a student asked for some intuition as to why, when you’re regressing y on x, measurement error on x biases the coefficient estimate but measurement error on y does not.

I gave the following quick explanation:
– You’re already starting with the model, y_i = a + bx_i + e_i. If you add measurement error to y, call it y*_i = y_i + eta_i, and then you regress y* on x, you can write y* = a + bx_i + e_i + eta_i, and as long as eta is independent of e, you can just combine them into a single error term.
– When you have measurement error in x, two things happen to attenuate b—that is, to pull the regression coefficient toward zero. First, if you spreading out x but keep y unchanged, this will reduce the slope of y on x. Second, when you add noise to x you’re changing the ordering of the data, which will reduce the strength of the relationship.

But that’s all words (and some math). It’s simpler and clearer to do a live simulation, which I did right then and there in class!

Here’s the R code:

# simulation for measurement error
library("arm")
set.seed(123)
n <- 1000
x <- runif(n, 0, 10)
a <- 0.2
b <- 0.3
sigma <- 0.5
y <- rnorm(n, a + b*x, sigma)
fake <- data.frame(x,y)

fit_1 <- lm(y ~ x, data=fake)
display(fit_1)

sigma_y <- 1
fake$y_star <- rnorm(n, fake$y, sigma_y)
sigma_x <- 4
fake$x_star <- rnorm(n, fake$x, sigma_x)

fit_2 <- lm(y_star ~ x, data=fake)
display(fit_2)

fit_3 <- lm(y ~ x_star, data=fake)
display(fit_3)

fit_4 <- lm(y_star ~ x_star, data=fake)
display(fit_4)

x_range <- range(fake$x, fake$x_star)
y_range <- range(fake$y, fake$y_star)

par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(1.5,.5,0), tck=-.01)
plot(fake$x, fake$y, xlim=x_range, ylim=y_range, bty="l", pch=20, cex=.5)
abline(coef(fit_1), col="red", main="No measurement error")
plot(fake$x, fake$y_star, xlim=x_range, ylim=y_range, bty="l", pch=20, cex=.5)
abline(coef(fit_2), col="red", main="Measurement error on y")
plot(fake$x_star, fake$y, xlim=x_range, ylim=y_range, bty="l", pch=20, cex=.5)
abline(coef(fit_3), col="red", main="Measurement error on x")
plot(fake$x_star, fake$y_star, xlim=x_range, ylim=y_range, bty="l", pch=20, cex=.5)
abline(coef(fit_4), col="red", main="Measurement error on x and y")

The resulting plot is at the top of this post.

I like this simulation for three reasons:

1. You can look at the graph and see how the slope changes with measurement error in x but not in y.

2. This exercise shows the benefits of clear graphics, including little things like making the dots small, adding the regression lines in red, labeling the individual plots, and using a common axis range for all four graphs.

3. It was fast! I did it live in class, and this is an example of how students, or anyone, can answer this sort of statistical question directly, with a lot more confidence and understanding than would come from a textbook and some formulas.

P.S. As Eric Loken and I discuss in this 2017 article, everything gets more complicated if you condition on "statistical significance."

P.P.S. Yes, I know my R code is ugly. Think of this as an inspiration: even if, like me, you’re a sloppy coder, you can still code up these examples for teaching and learning.

Why are all these school cheating scandals happening?

Paul Alper writes:

While the national scene is all about woke, book banning and the like, apparently Columbia University is still dealing with the long-standing conundrum, the best method to teach kids how to read.

He’s referring to this news article, “Amid Reading Wars, Columbia Will Close a Star Professor’s Shop,” which begins:

Lucy Calkins ran a beloved — and criticized — center at Teachers College for four decades. It is being dissolved. . . .

Her curriculum had teachers conduct “mini-lessons” on reading strategies, but also gave students plenty of time for silent reading and freedom to choose their own books. Supporters say those methods empower children, but critics say they waste precious classroom minutes, and allow students to wallow in texts that are too easy.

Some of the practices she once favored, such as prompting children to guess at words using the first letter and context clues, like illustrations, have been discredited.

Over the past three years, several prominent school districts — including New York City, the nation’s largest — dropped her program, though it remains in wide use. . . .

Critics of her ideas, including some cognitive scientists and instructional experts, said her curriculum bypassed decades of settled research, often referred to as the science of reading. That body of research suggests that direct, carefully sequenced instruction in phonics, vocabulary building and comprehension is more effective for young readers than Dr. Calkins’s looser approach.

Alper writes:

This article did not at all mention anything about language specifics. I bring this up because my granddaughters are in a Minneapolis Spanish immersion primary school. Because Spanish is almost 100 per cent phonetic, and English is terrible in this regard, they spell and read better in Spanish than they do in English. The mechanics of learning to read back in my day, was simple and devoid of theory or disagreement. You kept at it until you got it right. The it was English only because no accommodation was made for special needs, immigrants or for the outside world in general.

I know some people at Teachers College but I’ve never encountered Prof. Calkins, nor have I ever looked at the literature on language teaching. So I got nothin’ on this one.

But I did reply that the above story isn’t half as bad as this one from a few years back, which I titled, “What’s the stupidest thing the NYC Department of Education and Columbia University Teachers College did in the past decade?” It involved someone who was found to be a liar, a cheat, and a thief, and then, with that all known, was hired to two jobs as school principal! And then a Teachers College professor said, “We felt that on balance, her recommendations were so glowing from everyone we talked to in the D.O.E. that it was something that we just were able to live with.” This came out in the news after the principal in question was found do have “forged answers on students’ state English exams in April because the students had not finished the tests.” Quelle surprise, no? A liar/cheat/thief gets a new job doing the same thing and then does more lying and cheating (maybe no stealing that time, though).

Alper responded:

You wrote that in 2015 which is about the same time as this story which made Fani Willis RICO famous:

Her most prominent case was her prosecution of the Atlanta Public Schools cheating scandal. Willis, an assistant district attorney at the time, served as lead prosecutor in the 2014 to 2015 trial of twelve educators accused of correcting answers entered by students to inflate the scores of state administered standardized tests.

SAT and all the others did not exist in my 1950 NYC school days, but I believe we did have the so-called Regents Exams and they are still around. It never crossed my mind that the scoring of those exams was not on the up and up. Was I being naive? Was there more honesty and/or less messing around back then and it was just not financially worth it?

Here’s my response:

1. This particular form of cheating sounds no more easy or difficult now than in the past.

2. In the past (i.e., somewhere between 1950 and 2015), tests were important students but not so much for schools. So, yeah, students may have been motivated to cheat, but teachers and school administrators did not have any motivation, either to help students cheat, or to massively cheat on their own. Nowadays, tests can be high stakes for the school administrators, and so, for some of them, cheating is worth the risk.

Inspiring story from a chemistry classroom

From former chemistry teacher HildaRuth Beaumont:

I was reminded of my days as a newly qualified teacher at a Leicestershire comprehensive school in the 1970s, when I was given a group of reluctant pupils with the instruction to ‘keep them occupied’. After a couple of false starts we agreed that they might enjoy making simple glass ornaments. I knew a little about glass blowing so I was able to teach them how to combine coloured and transparent glass to make animal figures and Christmas tree decorations. Then one of them made a small bottle complete with stopper. Her classmate said she should buy some perfume, pour some of it into the bottle and give it to her mum as a Mother’s Day gift. ‘We could actually make the perfume too,’ I said. With some dried lavender, rose petals, and orange and lemon peel, we applied solvent extraction and steam distillation to good effect and everyone was able to produce small bottles of perfume for their mothers.

What a wonderful story. We didn’t do anything like this in our high school chemistry classes! Chemistry 1 was taught by an idiot who couldn’t understand the book he was teaching out of. Chemistry 2 was taught with a single-minded goal of teaching us how to solve the problems on the Advanced Placement exam. We did well on the exam and learned essentially zero chemistry. On the plus side, this allowed me to place out of the chemistry requirement in college. On the minus side . . . maybe it would’ve been good for me to learn some chemistry in college. I don’t remember doing any labs in Chemistry 2 at all!

“On the uses and abuses of regression models: a call for reform of statistical practice and teaching”: We’d appreciate your comments . . .

John Carlin writes:

I wanted to draw your attention to a paper that I’ve just published as a preprint: On the uses and abuses of regression models: a call for reform of statistical practice and teaching (pending publication I hope in a biostat journal). You and I have discussed how to teach regression on a few occasions over the years, but I think with the help of my brilliant colleague Margarita Moreno-Betancur I have finally figured out where the main problems lie – and why a radical rethink is needed. Here is the abstract:

When students and users of statistical methods first learn about regression analysis there is an emphasis on the technical details of models and estimation methods that invariably runs ahead of the purposes for which these models might be used. More broadly, statistics is widely understood to provide a body of techniques for “modelling data”, underpinned by what we describe as the “true model myth”, according to which the task of the statistician/data analyst is to build a model that closely approximates the true data generating process. By way of our own historical examples and a brief review of mainstream clinical research journals, we describe how this perspective leads to a range of problems in the application of regression methods, including misguided “adjustment” for covariates, misinterpretation of regression coefficients and the widespread fitting of regression models without a clear purpose. We then outline an alternative approach to the teaching and application of regression methods, which begins by focussing on clear definition of the substantive research question within one of three distinct types: descriptive, predictive, or causal. The simple univariable regression model may be introduced as a tool for description, while the development and application of multivariable regression models should proceed differently according to the type of question. Regression methods will no doubt remain central to statistical practice as they provide a powerful tool for representing variation in a response or outcome variable as a function of “input” variables, but their conceptualisation and usage should follow from the purpose at hand.

The paper is aimed at the biostat community, but I think the same issues apply very broadly at least across the non-physical sciences.

Interesting. I think this advice is roughly consistent with what Aki, Jennifer, and I say and do in our books Regression and Other Stories and Active Statistics.

More specifically, my take on teaching regression is similar to what Carlin and Moreno say, with the main difference being that I find that students have a lot of difficulty understanding plain old mathematical models. I spend a lot of time teaching the meaning of y = a + bx, how to graph it, etc. I feel that most regression textbooks focus too much on the error term and not enough on the deterministic part of the model. Also, I like what we say on the first page of Regression and Other Stories, about the three tasks of statistics being generalizing from sample to population, generalizing from control to treatment group, and generalizing from observed data to underlying constructs of interest. I think models are necessary for all three of these steps, so I do think that understanding models is important, and I’m not happy with minimalist treatments of regression that describe it as a way of estimating conditional expectations.

The first of these tasks is sampling inference, the second is causal inference, and the third refers to measurement. Statistics books (including my own) spend lots of time on sampling and causal inference, not so much on measurement. But measurement is important! For an example, see here.

If any of you have reactions to Carlin and Moreno’s paper, or if you have reactions to my reactions, please share them in comments, as I’m sure they’d appreciate it.

Our new book, Active Statistics, is now available!

Coauthored with Aki Vehtari, this new book is lots of fun, perhaps the funnest I’ve ever been involved in writing. And it’s stuffed full of statistical insights. The webpage for the book is here, and the link to buy it is here or directly from the publisher here.

With hundreds of stories, activities, and discussion problems on applied statistics and causal inference, this book is a perfect teaching aid, a perfect adjunct to a self-study program, and an enjoyable bedside read if you already know some statistics.

Here’s the quick summary:

This book provides statistics instructors and students with complete classroom material for a one- or two-semester course on applied regression and causal inference. It is built around 52 stories, 52 class-participation activities, 52 hands-on computer demonstrations, and 52 discussion problems that allow instructors and students to explore the real-world complexity of the subject. The book fosters an engaging “flipped classroom” environment with a focus on visualization and understanding. The book provides instructors with frameworks for self-study or for structuring the course, along with tips for maintaining student engagement at all levels, and practice exam questions to help guide learning. Designed to accompany the authors’ previous textbook Regression and Other Stories, its modular nature and wealth of material allow this book to be adapted to different courses and texts or be used by learners as a hands-on workbook.

It’s got 52 of everything because it’s structured around a two-semester class, with 13 weeks per semester and 2 classes per week. It’s really just bursting with material, including some classic stories and lots of completely new material. Right off the bat we present a statistical mystery that arose with a Wikipedia experiment, and we have a retelling of the famous Literary Digest survey story but with a new and unexpected twist (courtesy of Sharon Lohr and J. Michael Brick). And the activities have so much going on! One of my favorites is a version of the two truths and a lie game that demonstrates several different statistical ideas.

People have asked how this differs from my book with Deborah Nolan, Teaching Statistics: A Bag of Tricks. My quick answer is that Active Statistics has a lot more of everything, it’s structured to cover an entire two-semester course in order, and it’s focused on applied statistics. Including a bunch of stories, activities, demonstrations, and problems on causal inference, a topic that is not always so well integrated into the statistics curriculum. You’re gonna love this book.

You can buy it here or here. It’s only 25 bucks, which is an excellent deal considering how stuffed it is with useful content. Enjoy.

The four principles of Barnard College: Respect, empathy, kindness . . . and censorship?

A few months ago we had Uh oh Barnard . . .

And now there’s more:

Barnard is mandating that students remove any items affixed to room or suite doors by Feb. 28, after which point the college will begin removing any remaining items, Barnard College Dean Leslie Grinage announced in a Friday email to the Barnard community. . . .

“We know that you have been hearing often lately about our community rules and policies. And we know it may feel like a lot,” Grinage wrote. “The goal is to be as clear as possible about the guardrails, and, meeting the current moment, do what we can to support and foster the respect, empathy and kindness that must guide all of our behavior on campus.”

According to the student newspaper, here’s the full email from the Barnard dean:

Dear Residential Students,

The residential experience is an integral part of the Barnard education. Our small campus is a home away from home for most of you, and we rely on each other to help foster an environment where everyone feels welcome and safe. This is especially important in our residential spaces. We encourage debate and discussion and the free exchange of ideas, while upholding our commitment to treating one another with respect, consideration and kindness. In that spirit, I’m writing to remind you of the guardrails that guide our residential community — our Residential Life and Housing Student Guide.

While many decorations and fixtures on doors serve as a means of helpful communication amongst peers, we are also aware that some may have the unintended effect of isolating those who have different views and beliefs. So, we are asking everyone to remove any items affixed to your room and/or suite doors (e.g. dry-erase boards, decorations, messaging) by Wednesday, February 28 at noon; the College will remove any remaining items starting Thursday, February 29. The only permissible items on doors are official items placed by the College (e.g. resident name tags). (Those requesting an exemption for religious or other reasons should contact Residential Life and Housing by emailing [email protected].)

We know that you have been hearing often lately about our community rules and policies. And we know it may feel like a lot. The goal is to be as clear as possible about the guardrails, and, meeting the current moment, do what we can to support and foster the respect, empathy and kindness that must guide all of our behavior on campus.

The Residential Life and Housing team is always here to support you, and you should feel free to reach out to them with any questions you may have.

Please take care of yourselves and of each other. Together we can build an even stronger Barnard community.

Sincerely,

Leslie Grinage

Vice President for Campus Life and Student Experience and Dean of the College

The dean’s letter links to this Residential Life and Housing Student Guide, which I took a look at. It’s pretty reasonable, actually. All I saw regarding doors was this mild restriction:

While students are encouraged to personalize their living space, they may not alter the physical space of the room, drill or nail holes into any surface, or affix tapestries and similar decorations to the ceiling, light fixtures, or doorways. Painting any part of the living space or college-supplied furniture is also prohibited.

The only thing in the entire document that seemed objectionable was the no-sleeping-in-the-lounges policy, but I can’t imagine they would enforce that rule unless someone was really abusing the privilege. They’re not gonna send the campus police to wake up a napper.

So, yeah, they had a perfectly reasonable rulebook and then decided to mess it all up by not letting the students decorate their doors. So much for New York, center of free expression.

I assume what’s going on here is that Barnard wants to avoid the bad publicity that comes from clashes between groups of students with opposing political views. And now they’re getting bad publicity because they’re censoring students’ political expression.

The endgame seems to be to turn the college to some sort of centrally-controlled corporate office park. But that wouldn’t be fair. In a corporate office, they let you decorate your own cubicle, right?

Hand-drawn Statistical Workflow at Nelson Mandela

In September 2023 I taught a week-long course on statistical workflow at the Nelson Mandela African Institution of Science and Technology (NM-AIST), a public postgraduate research university in Arusha, Tanzania established in 2009.

NM-AIST – CENIT@EA

The course was hosted by Dean Professor Ernest Rashid Mbega and the Africa Centre for Research, Agricultural Advancement, Teaching Excellence and Sustainability (CREATES) through the Leader Professor Hulda Swai and Manager Rose Mosha.

Our case study was an experiment on the NM-AIST campus designed and implemented by Dr Arjun Potter and Charles Luchagula to study the effects of drought, fire, and herbivory on growth of various acacia tree species. The focus was pre-data workflow steps, i.e. experimental design. The goal for the week was to learn some shared statistical language so that scientists can work with statisticians on their research.

Together with Arjun and Charles, with input from Drs Emmanuel Mpolya, Anna Treydte, Andrew Gelman, Michael Betancourt, Avi Feller, Daphna Harel, and Joe Blitzstein, I created course materials full of activities. We asked participants to hand-draw the experimental design and their priors, working together with their teammates. We also did some pencil-and-paper math and some coding in R.

Course participants were students and staff from across NM-AIST. Over the five days, between 15 and 25 participants attended on a given day.

Using the participants’ ecological expertise, we built a model to tell a mathematical story of how acacia tree height could vary by drought, fire, herbivory, species, and plot location. We simulated parameters and data from this model, e.g. beta_fire = rnorm(n = 1, mean = -2, sd = 1) then simulated_data …= rnorm(n, beta_0 + beta_fire*Fire +… beta_block[Block], sd_tree). We then fit the model to the simulated data.

Due to difficulty in manipulating fire, fire was assigned at the block-level, whereas drought and herbivory were assigned at the sub-block level. We saw how this reduced precision in estimating the effect of fire:

We redid the simulation assuming a smaller block effect and saw improved precision. This confirmed the researcher’s intuitions that they need to work hard to reduce the block-to-block differences.

To keep the focus on concepts not code, we only simulated once from the model. A full design analysis would include many simulations from the model. In Section 16.6 of ROS they fix one value for the parameters and simulate multiple datasets. In Gelman and Carlin (2014) they consider a range of plausible parameters using prior information. Betancourt’s workflow simulates parameters from the prior.

Our course evaluation survey was completed by 14 participants. When asked “which parts of the class were most helpful to you to understand the concepts?”, respondents chose instructor explanations, drawings, and activities as more helpful than the R code. However, participants also expressed eagerness to learn R and to analyze the real data in our next course.

The hand-drawn course materials and activities were inspired by Brendan Leonard’s illustrations in Bears Don’t Care About Your Problems and I Hate Running and You Can Too. Brendan wrote me,

I kind of think hand-drawing stuff makes it more fun and also maybe less intimidating?

I agree.

More recently, I have been reading Introduction to Modern Causal Inference by Alejandro Schuler and Mark van der Laan, who say

It’s easy to feel like you don’t belong or aren’t good enough to participate…

yup.

To deal with that problem, the voice we use throughout this book is informal and decidedly nonacademic…Figures are hand-drawn and cartoonish.

I’m excited to return to NM-AIST to continue the workflow steps with the data that Dr Arjun Potter and Charles Luchagula have been collecting. With the real data, we can ask: is our model realistic enough to achieve our scientific goals ?

It’s bezzle time: The Dean of Engineering at the University of Nevada gets paid $372,127 a year and wrote a paper that’s so bad, you can’t believe it.

“As we look to sleep and neuroscience for answers we can study flies specifically the Drosophila melanogaster we highlight in our research.”

1. The story

Someone writes:

I recently read a paper of yours in the Chronicle about how academic fraudsters get away with it. I came across a strange case that I thought you would at least have some interest in when a faculty members owns an open access journal that costs to publish and then publishes a large number of papers in the journal.  The most recent issue is all from the same authors (family affair).

It is from an administrator at University of Nevada Reno.  This concern is related to publications within a journal that may not be reputable.   The Dean of Engineering has a number of publications in the International Supply Chain Technology Journal that are in question Google Scholar.  Normally, I would contact the editor, or publisher, but in this case, there are complexities.

This may not  be an issue but many of the articles are short, being 1 or 2 pages. In addition, some have a peer review process of 3 days or less. Another concern is that many of the papers do not even discuss what is in the title.  Take the following paper: It presents nothing about the title. Many of the papers read as if AI was used.

While the quality of these papers may not be of concern, the representation of these as publications could be. The person publishing them should have ethical standards that exceed those that are under his leadership. He is also the highest ranking official of the college of engineering and is expected to lead by example and be a good model to those under him.

If that is not enough, looking into the journal in more detail alludes to more ethical questions. The journal is published by PWD Group out of Texas. Lookup of PWD Group out of Texas yields that Erick Jones is the Director and President.  Erick Jones was also the Editor of the journal.  In addition to the journal articles, even books authored by Erick Jones are published by PWD.

Further looking into the journal publications you will see that there are a large number with Erick Jones Sr. and Erick Jones Jr.  There are also a large number with Felicia Jefferson.  Felicia is also a faculty member at UNR and the spouse of Dean Jones.  A few of the papers raise concerns related to deer supply chains. The following has a very fast peer review process of a few days and the caption of a white tailed deer is a reindeer. Another paper is even shorter, with a very fast peer review, and captions yet a different deer which is still not a white tail. It is unlikely these papers went through a robust peer review.

While these papers affiliation are prior to coming to UNR, the incoherence, conflict of interest, and incorrect data do lot look good for UNR and they were published either when Dr. Jefferson was applying to UNR or early upon her arrival. Similar issues with the timing of this article. Also, in the print version of the journal, Dr. Jefferson handles submissions (pp3).

Maybe this information is nothing to be concerned about.  At the very least, it sheds a poor light on the scientific process, especially when a Dean is the potential abuser.  It is not clear how he can encourage high quality manuscripts from other faculty when he has been able to climb the ladder using his own publishing house. I’ll leave you with a paper with a relevant title on minimizing train accidents through minimizing sleep deprivation. It seems like a really important study.  The short read should convince you otherwise and make you question the understanding of the scientific process by these authors.

Of specific concern is whether these publications led to he, or his spouse, being hired at UNR.  If these are considered legitimate papers, the entire hiring and tenure process at UNR is compromised.  Similar arguments exist if these papers are used in the annual evaluation process. It also raises a conflict of interest if he pays to publish and then receives proceeds on the back end.

I have no comment on the hiring, tenure, and evaluation process at UNR, or on any conflicts of interest. I know nothing about what is going on at UNR. It’s a horrifying story, though.

2. The published paper

OK, here it is, in its entirety (except for references). You absolutely have to see it to believe it:

Compared to this, the Why We Sleep guy is a goddamn titan of science.

3. The Dean of Engineering

From the webpage of the Dean of Engineering at the University of Reno:

Dr. Erick C. Jones is a former senior science advisor in the Office of the Chief Economist at the U.S. State Department. He is a former professor and Associate Dean for Graduate Studies at the College of Engineering at The University of Texas at Arlington.

From the press release announcing his appointment, dated July 01, 2022:

Jones is an internationally recognized researcher in industrial manufacturing and systems engineering. . . . “In Erick Jones, our University has a dynamic leader who understands how to seize moments of opportunity in order to further an agenda of excellence,” University President Brian Sandoval said. . . . Jones was on a three-year rotating detail at National Science Foundation where he was a Program Director in the Engineering Directorate for Engineering Research Centers Program. . . .

Jones is internationally recognized for his pioneering work with Radio Frequency Identification (RFID) technologies, Lean Six Sigma Quality Management (the understanding of whether a process is well controlled), and autonomous inventory control. He has published more than 243 manuscripts . . .

According to this source, his salary in 2022 was $372,127.

According to wikipedia, UNR is the state’s flagship public university.

I was curious to see what else Jones had published so I searched him on Google scholar and took a look at his three most-cited publications. The second of these appeared to be a textbook, and the third was basically 8 straight pages of empty jargon—ironic that a journal called Total Quality Management would publish something that has no positive qualities! The most-cited paper on the list was pretty bad too, an empty bit of make-work, the scientific equivalent of the reports that white-collar workers need to fill out and give to their bosses who can then pass these along to their bosses to demonstrate how productive they are. In short, this guy seems to be a well-connected time server in the Ed Wegman mode, minus the plagiarism.

He was a Program Director at the National Science Foundation! Your tax dollars at work.

Can you imagine what it would feel like to be a student in the engineering school at the flagship university of the state of Nevada, and it turns out the school is being run by the author of this:

Our recent study has the premise that both humans and flies sleep during the night and are awake during the day, and both species require a significant amount of sleep each day when their neural systems are developing in specific activities. This trait is shared by both species. An investigation was segmented into three subfields, which were titled “Life span,” “Time-to-death,” and “Chronological age.” In D. melanogaster, there was a positive correlation between life span, the intensity of young male medflies, and the persistence of movement. Time-to-death analysis revealed that the male flies passed away two weeks after exhibiting the supine behavior. Chronological age, activity in D. melanogaster was adversely correlated with age; however, there was no correlation between chronological age and time-to-death. It is probable that the incorporation the findings of age-related health factors and increased sleep may lead toless train accidents. of these age factors when considering these options supply chain procedure for maintaining will be beneficial.

I can’t even.

P.S. The thing I still can’t figure out is, why did Jones publish this paper at all? He’d already landed the juicy Dean of Engineering job, months before submitting it to his own journal. To then put his name on something so ludicrously bad . . . it can’t help his career at all, could only hurt. And obviously it’s not going to do anything to reduce train accidents. What was he possibly thinking?

P.P.S. I guess this happens all the time; it’s what Galbraith called the “bezzle.” We’re just more likely to hear about when it happens at some big-name place like Stanford, Harvard, Ohio State, or Cornell. It still makes me mad, though. I’m sure there are lots of engineers who are doing good work and could be wonderful teachers, and instead UNR spends $372,127 on this guy.

I’ll leave the last word to another UNR employee, from the above-linked press release:

“What is exciting about having Jones as our new dean for the College of Engineering is how he clearly understands the current landscape for what it means to be a Carnegie R1 ‘Very High Research’ institution,” Provost Jeff Thompson said. “He very clearly understands how we can amplify every aspect of our College of Engineering, so that we can continue to build transcendent programs for engineering education and research.”

They’re transcending something, that’s for sure.

My challenge for Jeff Thompson: Show up at an engineering class at your institution, read aloud the entire contents (i.e., the two paragraphs) of “Using Science to Minimize Sleep Deprivation that may reduce Train Accidents,” then engage the students in a discussion of what this says about “the current landscape for what it means to be a Carnegie R1 ‘Very High Research’ institution.”

Should be fun, no? Just remember, the best way to keep the students’ attention is to remind them that, yes, this will be covered on the final exam.

P.P.P.S. More here from Retraction Watch.

P.P.P.P.S. Still more here.

P.P.P.P.P.S. Retraction Watch found more plagiarism, this time on a report for the National Science Foundation.

Fun with Dååta: Reference librarian edition

Rasmuth Bååth reports the following fun story in a blog post, The source of the cake dataset (it’s a hierarchical modeling example included with the R package lme4).

Rasmuth writes,

While looking for a dataset to illustrate a simple hierarchical model I stumbled upon another one: The cake dataset in the lme4 package which is described as containing “data on the breakage angle of chocolate cakes made with three different recipes and baked at six different temperatures [as] presented in Cook (1938).

The search is on.

… after a fair bit of flustered searching, I realized that this scholarly work, despite its obvious relevance to society, was nowhere to be found online.

The plot thickens like cake batter until Megan N. O’Donnell, a reference librarian (officially, Research Data Services Lead!) at Iowa State, the source of the original, gets involved. She replies to Rasmuth’s query,

Sorry for the delay — I got caught up in a deadline. The scan came out fairly well, but page 16 is partially cut off. I’ll put in a request to have it professionally scanned, but that will take some time. Hopefully this will do for now.

Rasmuth concludes,

She (the busy Research Data Services Lead with a looming deadline) is apologizing to me (the random Swede with an eccentric cake thesis digitization request) that it took a few days to get me everything I asked for!?

Reference librarians are amazing! Read the whole story and download the actual manuscript from Rasmuth’s original blog post. The details of the experimental design are quite interesting, including the device used to measure cake breakage angle, a photo of which is included in the post.

I think it’d be fun to organize a class around generating new, small scale and amusing data sets like this one. Maybe it sounds like more fun than it would actually be—data collection is grueling. Andrew says he’s getting tired of teaching data communication, and he’s been talking a lot more about the importance of data collection on the blog, so maybe next year…

P.S. In a related note, there’s something called a baath cake that’s popular in Goa and confused my web search.

Resources for teaching and learning survey sampling, from Scott Keeter at Pew Research

Art Owen informed me that he’ll be teaching sampling again at Stanford, and he was wondering about ideas for students gathering their own data.

I replied that I like the idea of sampling from databases, biological sampling, etc. You can point out to students that a “blood sample” is indeed a sample!

Art replied:

Your blood example reminds me that there is a whole field (now very old) on bulk sampling. People sample from production runs, from cotton samples, from coal samples and so on. Widgets might get sampled from the beginning, middle and end of the run. David Cox wrote some papers on sampling to find the quality of cotton as measured by fiber length. The process is to draw a blue line across the sample and see the length of fibers that intersect the line. This gives you a length-biased sample that you can nicely de-bias. There’s also an interesting out there about tree sampling, literally on a tree, where branches get sampled at random and fruit is counted. I’m not sure if it’s practical.

Last time I found an interesting example where people would sample ocean tracts to see if there was a whale. If they saw one, they would then sample more intensely in the neighboring tracts. Then the trick was to correct for the bias that brings. It’s in the Sampling book by S. K. Thompson. There are also good mark-recapture examples for wildlife.

I hesitate to put a lot of regression in a sampling class; It is all too easy for every class to start looking like a regression/prediction/machine learning class. We need room for the ideas about where and how data arises and it’s too easy to crowd those out by dwelling on the modeling ideas.

I’ll probably toss in some space-filling sampling plans and other ways to down size data sets as well.

The old Cochran style was: get an estimator, show it is unbiased, find an expression for its variance, find an estimate of that variance, show this estimate is unbiased and maybe even find and compare variances of several competing variance estimates. I get why he did it but it can get dry. I include some of that but I don’t let it dominate the course. Choices you can make and their costs are more interesting.

I connected Art to Scott Keeter at Pew Research, who wrote:

Fortunately, we are pretty diligent about keeping track of what we do and writing it up. The examples below have lengthy methodology sections and often there is companion material (such as blog posts or videos) about the methodological issues.

We do not have a single overview methodological piece about this kind of work but the next best thing is a great lecture that Courtney Kennedy gave at the University of Michigan last year, walking through several of our studies and the considerations that went into each one:

Here are some links to good examples, with links to the methods sections or extra features:

Our recent study of Jewish Americans, the second one we’ve done. We switched modes for this study (thus different sampling strategy), and the report materials include an analysis of mode differences https://www.pewresearch.org/religion/2021/05/11/jewish-americans-in-2020/

Appendix A: Survey methodology

Jewish Americans in 2020: Answers to frequently asked questions

Our most recent survey of the US Muslim population:

U.S. Muslims Concerned About Their Place in Society, but Continue to Believe in the American Dream


A video on the methods:
https://www.pewresearch.org/fact-tank/2017/08/16/muslim-americans-methods/

This is one of the most ambitious international studies we’ve done:

Religion in India: Tolerance and Segregation


Here’s a short video on the sampling and methodology:
https://www.youtube.com/watch?v=wz_RJXA7RZM

We then had a quick email exchange:

Me: Thanks. Post should appear in Aug.

Scott: Thanks. We’ll probably be using sampling by spaceship and data collection with telepathy by then.

Me: And I’ll be charging the expenses to my NFT.

In a more serious vein, Art looked into Scott’s suggestions and followed up:

I [Art] looked at a few things at the Pew web-site. The quality of presentation is amazingly good. I like the discussions of how you identify who to reach out to. Also the discussion of how to pose the gender identity question is something that I think would interest students. I saw some of the forms and some of the data on response rates. I also found Courtney Kennedy’s video on non-probability polls. I might avoid religious questions for in-depth followup in class. Or at least, I would have to be careful in doing it, so nobody feels singled out.

Where could I find some technical documents about the American Trends Panel? I would be interested to teach about sample reweighting, e.g., raking and related methods, as it is done for real.

I’m wondering about getting survey data for a class. I might not be able to require them to get a Pew account and then agree to terms and conditions. Would it be reasonable to share a downsampled version of a Pew data set with a class? Something about attitudes to science would be interesting for students.

To which Scott replied:

Here is an overview I wrote about how the American Trends Panel operates and how it has changed over time in response to various challenges:

Growing and Improving Pew Research Center’s American Trends Panel

This relatively short piece provides some good detail about how the panel works:
https://www.pewresearch.org/fact-tank/2021/09/07/how-do-people-in-the-u-s-take-pew-research-center-surveys-anyway/

We use the panel to conduct lots of surveys, but most of them are one-off efforts. We do make an effort to track trends over time, but that’s usually the way we used to do it when we conducted independent sample phone surveys. However, we sometimes use the panel as a panel – tracking individual-level change over time. This piece explains one application of that approach:
https://www.pewresearch.org/fact-tank/2021/01/20/how-we-know-the-drop-in-trumps-approval-rating-in-january-reflected-a-real-shift-in-public-opinion/

When we moved from mostly phone surveys to mostly online surveys, we wanted to assess the impact of the change in mode of interview on many of our standard public opinion measures. This study was a randomized controlled experiment to try to isolate the impact of mode of interview:

From Telephone to the Web: The Challenge of Mode of Interview Effects in Public Opinion Polls

Survey panels have some real benefits but they come with a risk – that panelists change as a result of their participation in the panel and no longer fully resemble the naïve population. We tried to assess whether that is happening to our panelists:

Measuring the Risks of Panel Conditioning in Survey Research

We know that all survey samples have biases, so we weight to try to correct those biases. This particularly methodology statement is more detailed than is typical and gives you some extra insight into how our weighting operates. Unfortunately, we do not have a public document that breaks down every step in the weighting process:

Methodology

Most of our weighting parameters come from U.S. government surveys such as the American Community Survey and the Current Population Survey. But some parameters are not available on government surveys (e.g., religious affiliation) so we created our own higher quality survey to collect some of these for weighting:

How Pew Research Center Uses Its National Public Opinion Reference Survey (NPORS)

This one is not easy to find on our website but it’s a good place to find wonky methodological content, not just about surveys but about our big data projects as well:

Home


We used to publish these through Medium but decided to move them in-house.

By the way, my colleagues in the survey methods group have developed an R package for the weighting and analysis of survey data. This link is to the explainer for weighting data but that piece includes links to explainers about the basic analysis package:
https://www.pewresearch.org/decoded/2020/03/26/weighting-survey-data-with-the-pewmethods-r-package/

Lots here to look at!

It’s been awhile since I’ve taught a course on survey sampling. I used to teach such a course—it was called Design and Analysis of Sample Surveys—and I enjoyed it. But . . . in the class I’d always have to spend some time discussing basic statistics and regression modeling, and this always was the part of the class that students found the most interesting! So I eventually just started teaching statistics and regression modeling, which led to my Regression and Other Stories book. The course I’m now teaching out of that book is called Applied Regression and Causal Inference. I still think survey sampling is important; it was just hard to find an audience for the course.

Here’s how to subscribe to our new weekly newsletter:

Just a reminder: we have a new weekly newsletter. We posted on it a couple weeks ago; I’m just giving a reminder here because the goal of the newsletter is to reach people who wouldn’t otherwise go online to read the blog.

Subscribing is free, and then in your inbox each Monday morning you’ll get a list of our scheduled posts for the forthcoming week, along with links to the past week’s posts. Enjoy.

P.S. To subscribe, click on the link and follow the instructions from there.

Learning from mistakes (my online talk for the American Statistical Association, 2:30pm Tues 30 Jan 2024)

Here’s the link:

Learning from mistakes

Andrew Gelman, Department of Statistics and Department of Political Science, Columbia University

We learn so much from mistakes! How can we structure our workflow so that we can learn from mistakes more effectively? I will discuss a bunch of examples where I have learned from mistakes, including data problems, coding mishaps, errors in mathematics, and conceptual errors in theory and applications. I will also discuss situations where researchers have avoided good learning opportunities. We can then try to use all these cases to develop some general understanding of how and when we learn from errors in the context of the fractal nature of scientific revolutions.

The video is here.

It’s sooooo frustrating when people get things wrong, the mistake is explained to them, and they still don’t make the correction or take the opportunity to learn from their mistakes.

To put it another way . . . when you find out you made a mistake, you learn three things:

1. Now: Your original statement was wrong.

2. Implications for the future: Beliefs and actions that flow from that original statement may be wrong. You should investigate your reasoning going forward and adjust to account for your error.

3. Implications for the past: Something in your existing workflow led to your error. You should trace your workflow, see how that happened, and alter your workflow accordingly.

In poker, they say to evaluate the strategy, not the play. In quality control, they say to evaluate the process, not the individual outcome. Similarly with workflow.

As we’ve discussed many many times in this space (for example, here), it makes me want to screeeeeeeeeeam when people forego this opportunity to learn. Why do people, sometimes very accomplished people, give up this opportunity? I’m speaking here of people who are trying their best, not hacks and self-promoters.

The simple answer for why even honest people will avoid admitting clear mistakes is that it’s embarrassing for them to admit error, they don’t want to lose face.

The longer answer, I’m afraid, is that at some level they recognize issues 1, 2, and 3 above, and they go to some effort to avoid confronting item 1 because they really really don’t want to face item 2 (their beliefs and actions might be affected, and they don’t want to hear that!) and item 3 (they might be going about everything all wrong, and they don’t want to hear that either!).

So, paradoxically, the very benefits of learning from error are scary enough to some people that they’ll deny or bury their own mistakes. Again, I’m speaking here of otherwise-sincere people, not of people who are willing to lie to protect their investment or make some political point or whatever.

In my talk, I’ll focus on my own mistakes, not those of others. My goal is for you in the audience to learn how to improve your own workflow so you can catch errors faster and learn more from them, in all three senses listed above.

P.S. Planning a talk can be good for my research workflow. I’ll get invited to speak somewhere, then I’ll write a title and abstract that seems like it should work for that audience, then the existence of this structure gives me a chance to think about what to say. For example, I’d never quite thought of the three ways of learning from error until writing this post, which in turn was motivated by the talk coming up. I like this framework. I’m not claiming it’s new—I guess it’s in Pólya somewhere—, just that it will help my workflow. Here’s another recent example of how the act of preparing an abstract helped me think about a topic of continuing interest to me.

Progress in 2023, Charles edition

Following the examples of Andrew, Aki, and Jessica, and at Andrew’s request:

Published:

Unpublished:

This year, I also served on the Stan Governing Body, where my primary role was to help bring back the in-person StanCon. StanCon 2023 took place at the University of Washington in St. Louis, MO and we got the ball rolling for the 2024 edition which will be held at Oxford University in the UK.

It was also my privilege to be invited as an instructor at the Summer School on Advanced Bayesian Methods at KU Leuven, Belgium and teach a 3-day course on Stan and Torsten, as well as teach workshops at StanCon 2023 and at the University of Buffalo.

Postdoc at Washington State University on law-enforcement statistics

This looks potentially important:

The Center for Interdisciplinary Statistical Education and Research (CISER) at Washington State University (WSU) is excited to announce that it has an opening for a Post-Doctoral Research Associate (statistical scientist) supporting a new state-wide public data project focused on law enforcement. The successful candidate will be part of a team of researchers whose mission is to modernize public safety data collection through standardization, automation, and evaluation. The project will actively involve law enforcement agencies, state and local policymakers, researchers, and the public in data exploration and discovery. This effort will be accomplished in part by offering education and training opportunities fostering community-focused policing and collaborative learning sessions. The statistical scientist in this role will develop comprehensive educational materials, workshops, online courses, and training manuals designed to equip and empower law enforcement agencies, state and local policymakers, researchers, and the public with data and statistical literacy skills that will enable them to maximize the utility of the data project.

Data, education, and policy. Interesting.