데이터 과학을 위한 통계(4)Practical Statistics for Data Scientists (4)
데이터와 표본분포
신뢰구간
표본으로 계산한 평균이 100이라고 해서 모집단의 평균도 정확히 100이라고 말할 수는 없다. 다른 표본을 뽑았다면 다른 평균이 나왔을 수 있기 때문이다.
이때 추정값 하나만 제시하는 대신, 추정의 불확실성을 구간으로 나타내는 방법이 신뢰구간이다.
- 점추정 : 모평균처럼 알고 싶은 값을 하나의 수치로 추정하는 것
- 신뢰구간 : 표본을 이용해 구성한, 모수에 대한 구간 추정
- 신뢰수준 : 같은 절차로 표본추출과 구간 계산을 반복했을 때, 만들어진 구간이 참 모수를 포함하는 비율
- 구간끝점 : 신뢰구간의 하한과 상한
예를 들어 평균에 대한 95% 신뢰구간이 [90, 110]으로 계산되었다고 하자. 여기서 95%는 무엇을 의미할까?
같은 모집단에서 표본을 뽑아 같은 방법으로 신뢰구간을 만드는 일을 반복하면, 그 구간들 중 약 95%가 실제 모평균을 포함한다는 뜻이다.
빈도주의 관점에서 모평균은 고정된 값이고, 표본에 따라 달라지는 것은 구간이다. 따라서 이미 계산된 특정 구간에 대해 “모평균이 이 안에 있을 확률이 95%”라고 해석하는 것과는 구분해야 한다.
또한 95% 신뢰구간이 전체 데이터의 95%를 포함한다는 뜻은 아니다. 평균에 대한 신뢰구간은 개별 데이터가 퍼진 범위가 아니라, 모평균을 얼마나 정밀하게 추정했는지를 나타낸다.
부트스트랩을 이용한 신뢰구간
이전 글에서 살펴본 부트스트랩으로도 신뢰구간을 구할 수 있다. 그중 재표본 통계량의 분위수를 이용하는 방법을 백분위수 부트스트랩 신뢰구간이라고 한다.
표본의 크기가 일 때 계산 과정은 다음과 같다.
- 원래 표본에서 크기가 인 표본을 복원추출한다.
- 재표본의 평균처럼 관심 있는 통계량을 계산한다.
- 이 과정을 충분히 많이 반복하여 통계량들을 모은다.
- 통계량들을 크기순으로 정렬하고, 원하는 신뢰수준에 맞게 양 끝을 제외한다.
- 남은 부분의 양 끝값을 신뢰구간의 끝점으로 사용한다.
90% 신뢰구간을 구하려면 아래쪽 5%와 위쪽 5%를 제외한다. 따라서 부트스트랩 통계량의 5백분위수와 95백분위수가 구간끝점이 된다. 95% 신뢰구간에서는 2.5백분위수와 97.5백분위수를 사용한다.
이 방법은 평균뿐 아니라 중앙값처럼 다른 통계량에도 적용할 수 있다. 다만 부트스트랩도 원래 표본을 바탕으로 계산하므로, 대표성이 부족한 표본의 편향까지 해결해 주지는 않는다.
신뢰구간의 폭
신뢰구간의 폭은 추정의 불확실성을 보여준다. 다른 조건이 같다면 다음과 같은 관계가 있다.
- 신뢰수준이 높아지면 구간이 넓어진다.
- 표본크기가 커지면 일반적으로 구간이 좁아진다.
- 데이터의 변동성이 커지면 일반적으로 구간이 넓어진다.
같은 표본에서 계산한 99% 신뢰구간은 95% 신뢰구간보다 넓다. 더 높은 포함 비율을 얻으려면 그만큼 넓은 범위를 잡아야 하기 때문이다.
독립적인 관측값으로 계산한 평균의 표준오차는 다음과 같이 추정한다.
여기서 는 표본표준편차, 은 표본크기이다. 표본표준편차가 비슷하게 유지된다면 표본크기를 4배로 늘렸을 때 표준오차는 약 절반이 된다.
정규분포
정규분포는 평균을 중심으로 좌우가 대칭인 종 모양의 분포이다. 평균 가 중심의 위치를, 표준편차 가 퍼진 정도를 결정한다.
- 오차 : 관측값과 기준값 또는 예측값 사이의 차이
- 표준화 : 데이터에서 평균을 빼고 표준편차로 나누는 변환
- z 점수 : 평균에서 얼마나 떨어져 있는지를 표준편차 단위로 표현한 값
- 표준정규분포 : 평균이 0이고 표준편차가 1인 정규분포
- QQ 그림 : 두 분포의 분위수를 비교하는 그림. 정규분포와 표본의 분포를 비교할 때도 사용한다.
정규분포에서는 평균을 중심으로 다음과 같은 비율이 성립한다.
| 범위 | 포함되는 비율 |
|---|---|
| 약 68% | |
| 약 95% | |
| 약 99.7% |
이 비율은 정규분포에 대한 성질이다. 모든 데이터에 그대로 적용할 수 있는 규칙은 아니다.
소득이나 구매 금액처럼 한쪽으로 치우친 데이터도 많다. 정규분포의 중요성은 모든 원시 데이터가 이 분포를 따른다는 데 있지 않다. 적절한 조건에서 표본평균의 분포를 정규분포로 근사할 수 있다는 점이 통계적 추론에 중요하다.
이전 글의 중심극한정리도 원래 데이터 자체가 정규분포로 바뀐다는 뜻은 아니다. 독립성, 유한한 분산 등의 조건 아래에서 표본크기가 커지면, 표준화된 표본평균의 분포가 정규분포에 가까워진다는 의미이다.
표준정규분포와 z 점수
평균이 , 표준편차가 인 분포에서 값 를 표준화하면 다음과 같다.
모집단의 평균과 표준편차를 모르면 표본평균 와 표본표준편차 를 이용해 표준화할 수 있다.
예를 들어 평균이 70점이고 표준편차가 10점인 시험에서 90점을 받았다면 z 점수는 2이다. 평균보다 표준편차의 2배만큼 높은 위치라는 뜻이다.
데이터를 표준화한다고 해서 정규분포가 되는 것은 아니다.
표준화는 중심과 척도를 바꾸는 작업이다. 원래 분포가 비대칭이라면 표준화한 뒤에도 그 비대칭적인 모양은 유지된다. 원래 정규분포를 따르는 변수를 모집단 평균과 표준편차로 표준화했을 때 표준정규분포를 얻는다.
QQ 그림
데이터가 정규분포에 얼마나 가까운지 살펴보는 방법으로 QQ 그림(quantile-quantile plot)이 있다.
정규 QQ 그림은 다음 두 값을 비교한다.
- 가로축 : 정규분포의 이론적 분위수
- 세로축 : 크기순으로 정렬한 표본의 값 또는 표준화한 값
데이터가 정규분포에 가까우면 점들이 대체로 직선을 따라 놓인다. 반대로 점들이 체계적으로 휘거나 양 끝에서 크게 벗어나면 정규분포와 다른 특징이 있다는 신호이다.
예를 들어 중앙의 점들은 기준선에 가깝지만 왼쪽 끝은 선보다 아래로, 오른쪽 끝은 선보다 위로 벗어난다면, 정규분포보다 양쪽 꼬리에서 극단적인 값이 더 자주 나타나는 분포를 의심할 수 있다.
다만 작은 표본에서는 우연히 점들이 벗어날 수도 있다. QQ 그림은 분포의 특징을 파악하는 도구이지, 그림 하나만으로 정규성을 확정하는 방법은 아니다.
긴 꼬리 분포
실제 데이터는 정규분포보다 훨씬 큰 값이나 작은 값이 자주 나타날 수 있다. 분포의 중심에서 멀리 떨어진 부분을 꼬리라고 한다.
- 꼬리 : 분포의 양 끝에서 극단적인 값들이 나타나는 부분
- 왜도 : 분포가 좌우로 얼마나 비대칭적인지를 나타내는 지표
- 긴 꼬리 분포 : 이 절에서는 정규분포에 비해 극단적인 값이 상대적으로 자주 나타나는 분포를 가리킨다.
꼬리의 특성과 비대칭성은 구분해야 한다. 한쪽으로 치우친 분포뿐 아니라, 좌우 대칭인 분포도 정규분포보다 두꺼운 꼬리를 가질 수 있다.
책에서는 넷플릭스의 일별 주식 수익률에 대한 QQ 그림을 예로 든다. 중앙의 값들은 기준선에 비교적 가깝지만 양 끝의 값들은 크게 벗어난다. 이는 정규분포로 예상하는 것보다 극단적인 변동이 더 자주 나타날 수 있음을 보여준다.
이런 데이터를 정규분포로만 설명하면 드물지만 큰 변동을 과소평가할 수 있다. 데이터의 대부분이 모인 중앙뿐 아니라 꼬리에서 어떤 일이 일어나는지도 살펴봐야 한다.
또한 극단적인 값이 관측되었다고 해서 곧바로 오류로 판단해서는 안 된다. 입력 오류인지, 실제로 발생할 수 있는 현상인지 맥락을 확인해야 한다.
스튜던트의 t 분포
스튜던트의 t 분포는 표준정규분포처럼 좌우 대칭의 종 모양이지만, 꼬리가 더 두껍다. 모표준편차를 모르는 상황에서 표본평균에 대한 추론을 할 때 사용한다.
- : 표본크기
- 자유도 : 분포의 형태를 결정하는 값. 한 표본의 평균에 대한 t 추론에서는 일반적으로 이다.
- t 통계량 : 표본평균과 모평균의 차이를 추정한 표준오차로 나눈 값
정규모집단에서 독립적으로 표본을 뽑았을 때 다음 통계량은 자유도가 인 t 분포를 따른다.
여기서 는 표본평균, 는 표본표준편차이다.
모표준편차 를 모르기 때문에 표본에서 계산한 를 사용한다. 표준오차 자체도 추정해야 하므로 불확실성이 추가된다. t 분포의 두꺼운 꼬리는 이러한 불확실성을 반영한다.
표본평균 자체가 언제나 t 분포를 따르는 것은 아니다. 위와 같이 표본표준편차로 표준화한 통계량의 분포를 말한다는 점을 구분해야 한다.
자유도가 작을수록 꼬리가 두껍고, 자유도가 커질수록 표준정규분포에 가까워진다. 따라서 작은 표본에서 t 분포를 사용하면 같은 신뢰수준의 정규분포 임계값을 사용할 때보다 더 넓은 신뢰구간을 얻게 된다.
t 분포를 이용한 신뢰구간
모평균에 대한 양측 신뢰구간은 다음과 같이 계산한다.
여기서 은 자유도가 인 t 분포의 분위수이다. 95% 신뢰구간이라면 이므로 0.975 분위수를 사용한다.
이해를 위한 예로, 독립적인 표본 25개에서 평균이 100, 표본표준편차가 10이라고 하자. 정규모집단을 가정하면 자유도는 24이고, 95% 신뢰구간에 사용하는 t 임계값은 약 2.064이다.
정규모집단에서는 이 t 구간의 이론적 근거가 정확하게 성립한다. 모집단이 정규분포가 아니더라도 표본이 충분히 크면 근사적으로 사용할 수 있는 경우가 많다. 다만 표본이 작고 심하게 비대칭이거나 극단값의 영향이 큰 경우에는 적용 조건을 더 신중하게 살펴봐야 한다.
부트스트랩은 재표본추출로 통계량의 변동성을 추정하고, t 분포를 이용하는 방법은 이론적 분포와 표준오차를 이용한다. 두 방법 모두 표본에서 얻은 추정값에 어느 정도의 불확실성이 있는지 표현하는 데 사용된다.
Data and sampling distributions
Confidence intervals
Just because the mean computed from a sample is 100 doesn’t mean we can say the population mean is exactly 100. A different sample could have produced a different mean.
Instead of presenting a single estimate, a confidence interval expresses the uncertainty of the estimate as a range.
- Point estimate: estimating a quantity of interest, such as the population mean, as a single number
- Confidence interval: an interval estimate of a parameter, built from the sample
- Confidence level: the proportion of intervals that contain the true parameter when sampling and interval computation are repeated with the same procedure
- Interval endpoints: the lower and upper bounds of the confidence interval
Say a 95% confidence interval for the mean is computed as [90, 110]. What does the 95% mean?
If we repeatedly drew samples from the same population and built confidence intervals the same way, about 95% of those intervals would contain the true population mean.
From the frequentist point of view, the population mean is a fixed value; what varies from sample to sample is the interval. So this must be kept apart from interpreting one already-computed interval as “there is a 95% probability that the population mean lies in here.”
Also, a 95% confidence interval does not mean it contains 95% of the data. A confidence interval for the mean doesn’t describe how widely individual data points are spread; it describes how precisely the population mean has been estimated.
Confidence intervals with the bootstrap
The bootstrap from the previous post can also produce confidence intervals. The method that uses quantiles of the resampled statistics is called the percentile bootstrap confidence interval.
For a sample of size , the procedure is:
- Draw a sample of size with replacement from the original sample.
- Compute the statistic of interest, such as the mean of the resample.
- Repeat this enough times to collect many statistics.
- Sort the statistics and trim both ends according to the desired confidence level.
- Use the extreme values of what remains as the endpoints of the confidence interval.
For a 90% confidence interval, trim the bottom 5% and the top 5%, so the 5th and 95th percentiles of the bootstrap statistics become the endpoints. A 95% confidence interval uses the 2.5th and 97.5th percentiles.
This works not only for the mean but for other statistics such as the median. However, since the bootstrap still computes from the original sample, it does not fix the bias of a sample that lacks representativeness.
Width of a confidence interval
The width of a confidence interval shows the uncertainty of the estimate. With everything else equal, the following relationships hold.
- As the confidence level rises, the interval widens.
- As the sample size grows, the interval generally narrows.
- As the variability of the data grows, the interval generally widens.
A 99% confidence interval computed from the same sample is wider than a 95% one. To get a higher coverage rate, you have to take a correspondingly wider range.
The standard error of a mean computed from independent observations is estimated as follows.
Here is the sample standard deviation and is the sample size. If the sample standard deviation stays about the same, quadrupling the sample size roughly halves the standard error.
The normal distribution
The normal distribution is a bell-shaped distribution, symmetric around its mean. The mean sets the location of the center and the standard deviation sets the spread.
- Error: the difference between an observation and a reference or predicted value
- Standardization: transforming data by subtracting the mean and dividing by the standard deviation
- z-score: how far a value is from the mean, expressed in units of standard deviations
- Standard normal distribution: a normal distribution with mean 0 and standard deviation 1
- QQ plot: a plot comparing the quantiles of two distributions; also used to compare a sample’s distribution with the normal distribution
In a normal distribution, the following proportions hold around the mean.
| Range | Proportion included |
|---|---|
| about 68% | |
| about 95% | |
| about 99.7% |
These proportions are a property of the normal distribution. They are not a rule you can apply to every data set as is.
Plenty of data, such as income or purchase amounts, is skewed to one side. The importance of the normal distribution is not that all raw data follows it. What matters for statistical inference is that under suitable conditions, the distribution of the sample mean can be approximated by a normal distribution.
The central limit theorem from the previous post also doesn’t mean the original data itself turns normal. It means that under conditions such as independence and finite variance, as the sample size grows, the distribution of the standardized sample mean gets close to normal.
The standard normal distribution and z-scores
Standardizing a value from a distribution with mean and standard deviation gives:
If the population mean and standard deviation are unknown, you can standardize with the sample mean and the sample standard deviation .
For example, scoring 90 on a test with a mean of 70 and a standard deviation of 10 gives a z-score of 2. It means the score sits two standard deviations above the mean.
Standardizing data does not make it normally distributed.
Standardization changes the center and the scale. If the original distribution is asymmetric, that asymmetric shape survives standardization. You get the standard normal distribution when a variable that is already normally distributed is standardized with the population mean and standard deviation.
QQ plots
One way to see how close data is to a normal distribution is the QQ plot (quantile-quantile plot).
A normal QQ plot compares two things:
- Horizontal axis: the theoretical quantiles of the normal distribution
- Vertical axis: the sample values sorted in order, or their standardized values
If the data is close to normal, the points fall roughly along a straight line. If the points instead bend systematically or stray far at both ends, that signals features that differ from the normal distribution.
For example, if the points in the middle stay close to the reference line but the left end drops below it and the right end rises above it, you can suspect a distribution in which extreme values show up in both tails more often than under a normal distribution.
With small samples, though, points can stray by chance. A QQ plot is a tool for seeing the character of a distribution, not a way to settle normality from a single picture.
Long-tailed distributions
Real data can show values far larger or smaller than a normal distribution would, and show them often. The parts of a distribution far from its center are called the tails.
- Tail: the parts at both ends of a distribution where extreme values appear
- Skewness: a measure of how asymmetric a distribution is from left to right
- Long-tailed distribution: in this section, a distribution in which extreme values appear relatively more often than in a normal distribution
Tail behavior and asymmetry should be kept apart. Not only skewed distributions but symmetric distributions can also have heavier tails than the normal distribution.
The book uses a QQ plot of Netflix’s daily stock returns as an example. The values in the middle stay fairly close to the reference line, but the values at both ends stray far from it. This shows that extreme swings can happen more often than a normal distribution would predict.
Describing such data with a normal distribution alone can underestimate rare but large swings. You need to look not only at the center, where most of the data sits, but also at what happens in the tails.
And an observed extreme value shouldn’t be dismissed as an error right away. Check the context to see whether it is an input error or something that can really happen.
Student’s t-distribution
Student’s t-distribution is a symmetric bell shape like the standard normal distribution, but with heavier tails. It is used for inference about a sample mean when the population standard deviation is unknown.
- : sample size
- Degrees of freedom: the value that determines the shape of the distribution; for t inference on the mean of one sample it is usually
- t-statistic: the difference between the sample mean and the population mean, divided by the estimated standard error
When a sample is drawn independently from a normal population, the following statistic follows a t-distribution with degrees of freedom.
Here is the sample mean and is the sample standard deviation.
Because the population standard deviation is unknown, the computed from the sample is used instead. Since the standard error itself has to be estimated, extra uncertainty comes in. The heavy tails of the t-distribution reflect that uncertainty.
The sample mean itself does not always follow a t-distribution. Keep in mind that it is the distribution of the statistic standardized by the sample standard deviation, as above.
The fewer the degrees of freedom, the heavier the tails; as the degrees of freedom grow, it approaches the standard normal distribution. So using the t-distribution on a small sample gives a wider confidence interval than using normal critical values at the same confidence level.
Confidence intervals with the t-distribution
A two-sided confidence interval for the population mean is computed as follows.
Here is the quantile of the t-distribution with degrees of freedom. For a 95% confidence interval, , so the 0.975 quantile is used.
As an illustration, say 25 independent observations have a mean of 100 and a sample standard deviation of 10. Assuming a normal population, there are 24 degrees of freedom, and the t critical value for a 95% confidence interval is about 2.064.
For a normal population, the theoretical basis of this t interval holds exactly. Even when the population isn’t normal, it can often be used as an approximation if the sample is large enough. But when the sample is small and heavily skewed, or extreme values have a large influence, the conditions for using it deserve a closer look.
The bootstrap estimates the variability of a statistic by resampling, while the t-distribution approach uses a theoretical distribution and the standard error. Both are used to express how much uncertainty there is in an estimate obtained from a sample.