Showing posts with label probability. Show all posts
Showing posts with label probability. Show all posts

Saturday, 5 October 2019

book review: Risk Savvy

Gerd Gigerenzer.
Risk Savvy: how to make good decisions.
Penguin. 2014

There are two main points made in this book.

Firstly, you need to use a different reasoning process about situations where you know the risks and their odds, and the uncertain situations where you don’t; and you need to be able to distinguish these cases. In the case of uncertainty, rules of thumb are usually better than trying to calculate unknown odds. Gigerenzer gives some examples. I particularly liked his discussion of the real Monty Hall problem, rather than the “tidied up” version used for probability calculations. The real situation is much messier, and I have pointed out that you need to know the full rules beforehand: the stated solution works only if the host doesn’t cheat.

Secondly, even when the odds and risks are known, most statistics are so badly presented, possibly to make better headlines, that even the experts don’t understand what they say; you need to look at the real underlying rates. Behaviour X doubles the chance of cancer Y may not be a problem, if the chance of cancer Y is extremely small in the first place. Gigerenzer gives examples of a way to present rates rather than conditional probabilities that makes it much easier to see and understand the true risks.

There are many good cases discussed in here, with a large chunk of the book given over to healthcare. For example, there is a lot about medical screening, false positives, and increased “survival” rates being due entirely to earlier diagnosis, and nothing to do with living longer in total if diagnosed earlier (“lead time bias”). Survival rates are different from mortality rates.

Some of the discussions do feel a little disjointed. In particular, there is early emphasis on how most real world issues deal with uncertainty (rules of thumb) rather than risk (calculating odds), yet much of the book is on increasing statistical literacy. No matter; there is much good material in here.




For all my book reviews, see my main website.

Monday, 26 August 2019

book review: The Book of Why

Judea Pearl, Dana Mackenzie.
The Book of Why: the new science of cause and effect.
Penguin. 2018

We have all heard the old saying “correlation is not causation”. This is a problem for statistics, since all it can measure is correlation. Pearl here argues that this is because statisticians are restricting themselves too much, and that it is possible to do more. There is no magic; to get this more, you have to add something into the system, but that something is very reasonable: a causal model.

He organises his argument using the three-runged “ladder of causation”. On the bottom rung is pure statistics, reasoning about observations: what is the probability of recovery, found from observing these people who have taken a drug. The second rung allows reasoning about interventions: what is the probability of recovery, if I were to give these other people the drug. And the top rung includes reasoning about counterfactuals: what would have happened if that person had not received the drug?
 
Intervention (rung 2) is different from observation alone (rung 1) because the observations may be (almost certainly are) of a biassed group: observing only those who took the drug for whatever reason, maybe because they were already sick in a particular hospital, or because they were rich enough to afford it, or some other confounding variable. The intervention, however, is a different case: people are specifically given the drug. The purely statistical way of moving up to rung 2 is to run a randomised control trial (RCT), to remove the effect of confounding variables, and thereby to make the observed results the same as the results from intervention. The RCT is often known as the “gold standard” for experimental research for this reason.

But here’s the thing: what is a confounding variable, and what is not? In order to know what to control for, and what to ignore, the experimenter has to have some kind of implicit causal model in their head. It has to be implicit, because statisticians are not allowed to talk about causality! Yet it must exist to some degree, otherwise how do we even know which variables to measure, let alone control for? Pearl argues to make this causal model explicit, and use it in the experimental design. Then, with respect to this now explicit causal model, it is possible to reason about results more powerfully. (He does not address how to discover this model: that is a different part of the scientific process, of modelling the world. However, observations can be used to test the model to some degree: some models are simply too causally strong to support the observed situation.)

Pearl uses this framework to show how and why the RCT works. More importantly, he also shows that it is possible to reason about interventions sometimes from observations alone (hence data mining pure observations becomes more powerful), or sometimes with fewer controlled variables, without the need for a full RCT. This is extremely useful, since there are many cases where RCTs are unethical, impractical, or too expensive. RCTs are not the “gold standard” after all; they are basically a dumb sledgehammer approach. He also shows how to use the causal model to calculate which variables do need to be controlled for, and how controlling for certain variables is precisely the wrong thing to do.

Using such causal models also allows us to ascend to the third rung: reasoning about counterfactuals, where experiments are in principle impossible. This gives us power to reason about different worlds: What’s the probability that Fred would have died from lung cancer if he hadn’t smoked? What’s the probability that heat wave would have happened with less CO2 in the atmosphere?
[p51] probabilities encode our beliefs about a static world, causality tells us whether and how probabilities change when the world changes, be it by intervention or by act of imagination. 

This is a very nicely written book, with many real world examples. The historical detail included shows how and why statisticians neglected causality. It is not always an easy read – the concepts are quite intricate in places – but it is a crucially important read. We should never again bow down to “correlation is not causation”: we now know how to discover when it is.

Highly recommended.




For all my book reviews, see my main website.

Wednesday, 10 June 2015

How many times should you run your simulation?

You have a new algorithm, say an evolutionary algorithm.  You want to show it is better than another algorithm.  But its behaviour is stochastic, varying from run to run.  How many times do you need to run it to show what you want to show?  How big a sample of possible results do you need? 10?  100?  1000?  More?

This is a known problem, solved by statisticians, used by scientists who want to know how many experiments they need to run to investigate their hypotheses.

First I recall some statistical terminology (null hypothesis, statistical significance, statistical power, effect size), then describe the way to calculate how many runs you need, using this terminology.  If you know this terminology, you can skip ahead to the final table.

null hypothesis

The null hypothesis, H0, is usually a statement of the status quo, of the null effect: the treatment has no effect; the algorithm has the same performance; etc.  The alternative hypothesis, H1, is that the effect is not null.  You are (usually) seeking to refute the null hypothesis in favour of the alternative hypothesis.

statistical significance and statistical power

Given a null hypothesis H0 and a statistical test, there are four possibilities.  H0 may or may not be true, and the test may or may not refute it.

H0 true H0 false
refute H0 type I error, false positive correct
fail to refute H0 correct type II error, false negative

The type I error, or false positive, erroneously concludes that the null hypothesis is false; that is, that there is an effect when there is not. The probability of this error (of refuting H0 given that H0 is true) is called α, or the statistical significance level.

     Î± = prob(refute H0|H0) = prob(false positive)

The type II error, or false negative, erroneously fails to refute the null hypothesis; that is, it is a failure to detect an effect that exists.  The probability of this error (of not refuting H0, given that H0 is not true) is called β.

     Î² = prob(not refute H0|not H0) = prob(false negative)

1−β is called the statistical power of the test, the probability of correctly refuting H0 when H0 is not true.

     power = 1−β = prob(refute H0|not H0)

Clearly, we would like to minimise both Î± and β, minimising both false positives and false negatives.  However, these aims are in conflict.  For example, we could trivially minimise Î± by never refuting H0, but this would maximise β, and vice versa.  The smaller either of them needs to be, the more runs are needed.

Different problems might put different emphasis on Î± and β.  Consider the case of illness diagnosis, versus your new algorithm.

Diagnosic test for an illness

  • false positive: the test detect illness when there is none, which might result in worry and unnecessary treatment
  • false negative: the test fails to detect the illness, which might result in death
So minimising Î² may take preference in such a case.

New evolutionary algorithm

  • false positive: you claim your algorithm is better when it isn’t; this will be embarrassing for you later when more runs fail to support your claim
  • false negative: you fail to detect that your algorithm is better; so you don’t publish
So minimising Î± may take preference in such a case.

p-value

A statistical test results in a p-value.  p is the probability of observing an effect, given that the null hypothesis holds.

     p = prob(obs|H0)

A low p-value means a low probability of observing the effect if H0 holds; the conclusion is then that H0 (probably) doesn’t hold.  We refute H0 with confidence level 1−p.

To refute H0 we want the observed p-value to be less than the initially chosen statistical significance Î±.  A typical confidence level is 95%, or Î± = 0.05.

effect size

The more runs we make, the smaller Î± and Î² can be.  That means we can refute H0 at higher and higher confidence level.  In fact, with enough runs we can refute almost any null hypothesis at a given confidence level, since any change to an algorithm probably makes some difference to the outcome.

Alternatively, we can use the higher number of runs to detect smaller and smaller deviations from H0.

For example, if H0 is that the means of the two samples A and B are the same:

     H0 : μA = μB

and the alternative hypothesis H1 is that the means are different:

     H1 : μA ≠ μB

then with more runs we can detect smaller and smaller differences in the means at a given significance level.  We can measure a smaller and smaller effect size.

Cohen’s d is one measure of effect size for normally distributed samples: the difference in means normalised by the standard deviation:

     d = (μA − μB) / σ

So an effect size of 1 occurs when the means are separated by one standard deviation.  Cohen gives names to different effect sizes: he calls 0.2 “small”, 0.5 “medium”, and 0.8 “large” effect sizes.  The smaller the effect size you want to detect, the more runs you need.

d = 0.2, “small”

d = 0.5, “medium”

d = 0.8, “large”

“Small” effect sizes might be fine in certain cases, where a small difference can nevertheless be valuable (either in a product, or in a theory).  However, for an algorithm to be worth publishing, you should probably aim for at least a “medium” effect size, if not a “large” one.

sample size

The required sample size, or number of runs, n, depends on your desired values of three parameters: (i) statistical significance Î±, (ii) statistical power 1−β, and (iii) effect size d.

For two samples of the same size, normally distributed, with H0 : Î¼A = Î¼B, then

     n = 2( (z(1−α/2)+z(1−β)) / d)2

where z is the inverse normal cumulative probability distribution function.  In the case of a single sample A compared against a fixed mean value, H0 : Î¼A = Î¼0, this number can be halved.

A Python script that calculates this value of n (rounded up to an integer) is
from math import ceil
from scipy.stats import norm
n = ceil( 2 * ( (norm.ppf ppf(1-alpha/2) + norm.ppf ppf(power) ) / d ) **2 )


If you want a significance at the 95% level (α = 0.05), and a power of 90%, and want to detect a large effect, then you need 33 runs; if you want to detect a medium effect you need 85 runs, and to detect a small effect you need over 500 runs.  (These numbers are based on the assumption that your samples are normally distributed.  Similar results follow for other distributions.)

At first sight, it might seem strange that the number of runs is somehow independent of the “noisiness” of the algorithm: why don’t we need more runs for an inherently noisy algorithm (large standard deviation) than from a very stable one (small standard deviation)?  The reason is because the effect size is also dependent on the standard deviation: for a given difference in the means, the effect size decreases as the standard deviation increases.  

So there you have it.  You don’t have to guess the number of runs, or just do “lots” to be sure: you can calculate n.  And it’s probably less than you would have guessed.



Wednesday, 26 March 2014

t distribution

… and do read the hovertext




For all my social networking posts, see my Google+ page

Saturday, 1 February 2014

quantum walking


It’s possible to build a quantum random walk simulator in Python/NumPy with code that is very close to the mathematical definitions.  Here’s how.

First, we need to import NumPy (to do the array operations) and matplotlib (to visualise the results).
from numpy import *
from matplotlib.pyplot import *
We define the number of steps, +++N+++, that we are going to walk.  We also define the total number of different positions the walker can be in after +++N+++ steps.
N = 100      # number of random steps
P = 2*N+1    # number of positions

a quantum coin

We toss a quantum coin to decide whether to go left or right (or a superposition).  In ket notation, we can write a general quantum coin as an arbitrary superposition of two states:
$$| coin \rangle = a | 0 \rangle_c + b | 1 \rangle_c; \mbox{ where} |a|^2 + |b|^2 = 1$$
The ket notation is a convenient shorthand for the actual vectors representing the state:
$$| 0 \rangle_c  = \left( \begin{array}{c}
1  \\
0  \end{array} \right);\ | 1 \rangle_c  = \left( \begin{array}{c}
0  \\
1  \end{array} \right)$$
So we can use a NumPy array to define a coin state:
coin0 = array([1, 0])  # |0>
coin1 = array([0, 1])  # |1>

the Hademard coin operator

We will see terms like +++| 0 \rangle_c \langle 0 |+++ in what follows.  This is the outer product of the relevant vectors, resulting in a matrix.  We can use NumPy to calculate these:
C00 = outer(coin0, coin0)  # |0><0| 
C01 = outer(coin0, coin1)  # |0><1| 
C10 = outer(coin1, coin0)  # |1><0| 
C11 = outer(coin1, coin1)  # |1><1| 
Quantum operators are unitary matrices.  The coin operator, that can be used to flip a quantum coin into a superposition, is:
$$\hat{C} = \frac{1}{\sqrt{2}} \left( | 0 \rangle_c \langle 0 | + | 0 \rangle_c \langle 1 | + | 1 \rangle_c \langle 0 | - | 1 \rangle_c \langle 1 | \right)$$
C_hat = (C00 + C01 + C10 - C11)/sqrt(2.)

position on a line

In ket notation, we can write the fully general position of the walker on the line as an arbitrary superposition of the +++P+++ possible states:
$$| posn \rangle = \sum_k \alpha_k | k \rangle_p ; \mbox{ where} \sum_k | \alpha_k |^2 = 1 $$

shift (step) operator

The step operator moves left or right along the line, depending on the value of the coin:
$$\hat{S} = | 0 \rangle_c \langle 0 | \otimes \sum_k | k+1 \rangle_p \langle k | + | 1 \rangle_c \langle 1 | \otimes \sum_k | k-1 \rangle_p \langle k |  $$
We assume the line is actually on a circle, so the positions at the ends wrap around.  However, we will always make the circle big enough so that this doesn’t happen during a walk.  The tensor product +++\otimes+++ is implemented with the NumPy kron operation:
ShiftPlus = roll(eye(P), 1, axis=0)
ShiftMinus = roll(eye(P), -1, axis=0)
S_hat = kron(ShiftPlus, C00) + kron(ShiftMinus, C11)

walk operator

The walk operator combines the coin operator on the coin state, and a step operator on the combined coin and position state:
$$\hat{U} = \hat{S} \left( \hat{C} \otimes \hat{\bf I}_p \right)$$
U = S_hat.dot(kron(eye(P), C_hat))

initial state

Let’s take the initial state of the system to be a coin in a superposition of left and right, and the walker at position 0:
$$ | \psi \rangle_0 = | coin \rangle_0 \otimes | posn \rangle_0 = \frac{1}{\sqrt{2}} \left( | 0 \rangle_c + i | 1 \rangle_c\right) \otimes | 0 \rangle_p$$
posn0 = zeros(P)
posn0[N] = 1     # array indexing starts from 0, so index N is the central posn
psi0 = kron(posn0,(coin0+coin1*1j)/sqrt(2.))

state after +++N+++ steps

Then walking +++N+++ steps is just applying the walk operator +++N+++ times:
$$ | \psi \rangle_N = \hat{U}^N | \psi \rangle_0$$
psiN = linalg.matrix_power(U, N).dot(psi0)
And we’re done! +++ | \psi \rangle_N+++ is the state of the system after +++N+++ random quantum steps.

measurement operator

We can measure the state at position +++k+++ using the measurement operator
$$\hat{M}_k = \hat{\bf I}_c \otimes | k \rangle_p \langle k |$$
We can use this to build up an array of probabilities, by taking the modulus squared of the state value at each position. (We can calculate the whole distribution in one go in simulation, but we would only get one measurement per experiment on the real quantum system.)
prob = empty(P)
for k in range(P):
    posn = zeros(P)
    posn[k] = 1     
    M_hat_k = kron( outer(posn,posn), eye(2))
    proj = M_hat_k.dot(psiN)
    prob[k] = proj.dot(proj.conjugate()).real

plot the distribution

We can then plot the probabilities.
fig = figure()
ax = fig.add_subplot(111)

plot(arange(P), prob)
plot(arange(P), prob, 'o')
loc = range (0, P, P / 10) #Location of ticks
xticks(loc)
xlim(0, P)
ax.set_xticklabels(range (-N, N+1, P / 10))

show()

For +++N=100+++ we get
probability distribution for a quantum random walk with +++N=100+++, symmetric initial coin

The maximum probability occurs at +++\approx N/\sqrt{2}+++.

If instead of starting with a symmetric initial coin, we start with +++|0\rangle_c+++, we get
probability distribution for a quantum random walk with +++N=100+++, initial coin +++|0\rangle+++
In neither case do these look anything like the bell curve of a classical random walk, with its maximum probability at +++0+++.  If you are drunk and trying to stagger home, best be quantum!

What I find most impressive about the Python is how closely we can make the code follow the mathematical formalism thoughout.

Saturday, 21 September 2013

95 percent confident that you're wrong

Be careful of statistical significance!
Ah, some scientists would say, maybe you can’t conclude anything with certainty. But with only a 5 percent chance of observing the data if there’s no effect, there’s a 95 percent chance of an effect—you can be 95 percent confident that your result is real. The problem is, that reasoning is 100 percent incorrect. For one thing, the 5 percent chance of a fluke is calculated by assuming there is no effect. If there actually is an effect, the calculation is no longer valid. Besides that, such a conclusion exemplifies a logical fallacy called “transposing the conditional.”
(via  Charlotte Bouckaert)

For all my social networking posts, see my Google+ page

Monday, 17 December 2012

cue spooky music

I've written about coincidences before, and I said: "things like this happen all the time".  Just to demonstrate this a bit further, here's another one (or maybe two, or even three).

This summer we holidayed in Northumbria, and had a day on Lindisfarne.  A colleague from Scotland commented that he'd been there at exactly the same time. The final photo in the post had a couple of birds in the background; I asked a bird-savvy friend to help identify them.  When they replied, the mentioned they had been on a cycling holiday in Northumbria, and close to Lindisfarne at this time!

Last week at work we had a Christmas quiz.  One of the questions was "what element is named after a Scottish village?"  I'd never heard of this one (if they'd said Sweden instead of Scotland, I could have done better), but one of our team-mates said "Strontium".

I'd forgotten about the Lindisfarne coincidence until I received the bird friend's Christmas letter, where they mentioned their Northumbria cycling holiday. They also mentioned an earlier holiday in Scotland, where they had spent a week "in a village called Strontian".

Cue spooky music.

Saturday, 2 June 2012

a jewel of a probability puzzle

I've been spending way too much time reading John Baez' Azimuth blog. It's got lots of fascinating stuff, but one piece that really caught my eye is a probability puzzle:
Suppose I have a box of jewels. The average value of a jewel in the box is \$10. I randomly pull one out of the box. What’s the probability that its value is at least \$100?
First thought, of course, is: "I don't have enough information; the answer will depend on the distribution".  But in fact you can give quite a strong bound on the answer even without knowing the distribution, using Markov's inequality: the probability is +++\le 1/10+++.

At first, this looks impossible: how can this be independent of the distribution?  Surely I can have some strange collection of jewels that violates this bound?  But no, and in the comments section there are some great explanations that give an intuition about why this is so, including David Guild's:
As long as gems have non-negative value, then (probability of pulling a \$100 or better gem > 10%) implies that (average value > \$10). Since the average is exactly \$10, then the probability can’t be more than 10%.
A very clear proof is laid out by Greg Egan. I'll rework it here, for the general case of an average value of +++a+++ (rather than the specific \$10) and a big value of +++b+++ (rather than \$100), to get the general result.

Let +++A+++ be the set of all jewels, +++\#A+++ be the size of set +++A+++, and +++V(x)+++ be the value of jewel +++x+++. Let +++B+++ be the set of "big value" jewels
$$ B = \{x\in A | V(x) \ge b\}$$We know the average value of the jewels is +++a+++:
$$ a =  \frac{1}{\#A} \sum_{x \in A} V(x) $$If we replace the sum over all jewels +++A+++ with the sum over the smaller set of jewels +++B+++, we must get a smaller answer (assuming that all the values are non-negative: necessary in the general case, and implicit in the given example).  So:
$$ a \ge  \frac{1}{\#A} \sum_{x \in B} V(x) $$From the definition of +++B+++, we have +++\forall x \in B, V(x) \ge b+++.  This implies that
$$ \frac{1}{\#A} \sum_{x \in B} V(x) \ge  \frac{1}{\#A} \sum_{x \in B} b  $$We can do this last sum:
$$ \frac{1}{\#A} \sum_{x \in B} b =  \frac{\#B}{\#A} b$$Putting this all together, we have
$$ a \ge  \frac{1}{\#A} \sum_{x \in B} V(x)  \ge \frac{1}{\#A} \sum_{x \in B} b = \frac{\#B}{\#A} b$$So
$$ a \ge  \frac{\#B}{\#A} b$$Rearranging gives the result that the proportion of big value items to all items (the probability of drawing a big value item) is:
$$ \frac{\#B}{\#A} \le \frac{a}{b}$$For the example with +++a=10+++ and +++b = 100+++, this gives us +++1/10+++.

This derivation assumes that the chance of pulling out any jewel is the same.  But, as Baez explains, the result is independent of this.  If some jewels are more likely to be picked, and that likelihood is used to define the average value too, then the result stands. (I leave the proof as an exercise for the reader.)

So, from a problem that initially looked as if it doesn't have nearly enough information, we've moved to an intuition about why a result (albeit only a bound) can be given, and a simple proof of a general result for that bound: Markov's inequality.  The power of maths!

There's also a result for values that can go negative, which requires also knowing the standard deviation: Chebyshev's  inequality.  It's all on John Baez' blog.  Go there, and you to  might spend as much time reading around as I have!

Sunday, 13 March 2011

Coincidence!

I've only recently started this intermittent blog, and a few days ago I sent off an email to a friend, notifying him of its existence. We haven't communicated for a few months, so it was amusing to get back the response:
(interesting stuff about stuff ....)
Hey, I was in the middle of this when YOUR e-mail came in! Telepathy?
Now, I know he doesn't really think it's telepathy, but some people do get exercised about this sort of coincidence. But things like this happen all the time. And it's easy to see why.

It might seem like the question is: "What's the chance of me receiving an email from you just as I'm writing one to you, given we haven't emailed each other for ages?" Pretty small, I suspect. But actually, the question is really: "What's the chance of me receiving an email from you just as I'm writing one to you, given we haven't emailed each other for ages, and given that I've just received an email from you just as I'm writing you one?". That is, what is p(x|x) (the probability of x having happened, given that x has happened)? Well, it's one. You can't get less unlikely than that!

Okay, that seems a little unsatisfactory. It still seems somehow to be remarkably unlikely. What's the probability it will happen again? Very small. But what's the probability that some weird coincidence will happen again? Now that is rather high.

Let's assume that we think some event has a probability of one in a gazillion of happening (the probability prior to it actually having happened, that is). But there are equally gazillions of unlikely things that could happen. Say you get an email from a friend just as you were thinking of them. But they might have phoned you, or texted you, or visited you, or written to you. Or you might have seen them on TV, or read about them, or about someone with the same name. And you could have been thinking of any of your friends, or of anyone else, or of anything else.

There are oodles of possible unlikely coincidences. What are the odds that one of them happens?

The way probability works, it's easier to calculate the chance of none of them happening. Let's say the odds of each one of these things happening is one in N, where N is very large (one in a billion, one in a trillion, or more). So the probability is 1/N, and the probability of it not happening is 1-1/N (very nearly, but not quite, certain that it won't happen).

Now let's say the number of unlikely things that might happen is also this huge number N (it could be 10N, or N/10; the calculation is cleaner using N, but the overall flavour of the result still holds for other values).What is the probability that none of the N unlikely things happens? That is, what is the probability that the first thing doesn't happen, and the second thing doesn't happen, and ... all the way up to and the Nth thing doesn't happen?

We just multiply the individual probabilities together, so we get (1-1/N)^N. That's the probability of no coincidences, so the probability of at least one coincidence is p = 1-(1-1/N)^N. For N larger that about 100, p is about 63% (for 10N it's 99.99%, for N/10 it's 10%). That's a pretty good chance of a weird coincidence. And that's just today!

The moral is: when individual events are unlikely, but there are also a lot of events that could happen, something will almost certainly occur.

So, that email: unlikely coincidence? That coincidence, yes; some sort of coincidence happening, not really.