샘플 데이터에서 신뢰 구간 계산
정규 분포를 가정하여 신뢰 구간을 계산하려는 샘플 데이터가 있습니다.
numpy 및 scipy 패키지를 찾아 설치했으며 평균과 표준 편차를 반환하기 위해 numpy를 얻었습니다 (데이터가 목록 인 numpy.mean (data)). 샘플 신뢰 구간을 얻는 것에 대한 조언을 주시면 감사하겠습니다.
import numpy as np
import scipy.stats
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
이렇게 계산할 수 있습니다.
배열 평균의 95 % 신뢰 구간을 계산하는 shasan 코드의 단축 버전입니다 a
.
import numpy as np, scipy.stats as st
st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))
그러나 StatsModels의 tconfint_mean을 사용하는 것이 틀림없이 더 좋습니다 .
import statsmodels.stats.api as sms
sms.DescrStatsW(a).tconfint_mean()
두 가지 모두에 대한 기본 가정은 표본 (배열 a
)이 표준 편차를 알 수없는 정규 분포와 독립적으로 추출되었다는 것입니다 ( MathWorld 또는 Wikipedia 참조 ).
큰 표본 크기 n의 경우 표본 평균은 정규 분포 st.norm.interval()
를 따르며 다음을 사용하여 신뢰 구간을 계산할 수 있습니다 (Jaime의 설명에서 제 안됨). 그러나 위의 솔루션은 st.norm.interval()
너무 좁은 신뢰 구간 (예 : "가짜 신뢰")을 제공 하는 작은 n에 대해서도 정확합니다 . 자세한 내용 은 비슷한 질문에 대한 내 대답 을 참조하십시오 (그리고 여기에 Russ의 의견 중 하나).
다음은 올바른 옵션이 (본질적으로) 동일한 신뢰 구간을 제공하는 예입니다.
In [9]: a = range(10,14)
In [10]: mean_confidence_interval(a)
Out[10]: (11.5, 9.4457397432391215, 13.554260256760879)
In [11]: st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a))
Out[11]: (9.4457397432391215, 13.554260256760879)
In [12]: sms.DescrStatsW(a).tconfint_mean()
Out[12]: (9.4457397432391197, 13.55426025676088)
마지막으로 다음을 사용하는 잘못된 결과 st.norm.interval()
:
In [13]: st.norm.interval(0.95, loc=np.mean(a), scale=st.sem(a))
Out[13]: (10.23484868811834, 12.76515131188166)
Start with looking up the z-value for your desired confidence interval from a look-up table. The confidence interval is then mean +/- z*sigma
, where sigma
is the estimated standard deviation of your sample mean, given by sigma = s / sqrt(n)
, where s
is the standard deviation computed from your sample data and n
is your sample size.
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module:
from statistics import NormalDist
def confidence_interval(data, confidence=0.95):
dist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + confidence) / 2.)
h = dist.stdev * z / ((len(data) - 1) ** .5)
return dist.mean - h, dist.mean + h
This:
Creates a
NormalDist
object from the data sample (NormalDist.from_samples(data)
, which gives us access to the sample's mean and standard deviation viaNormalDist.mean
andNormalDist.stdev
.Compute the
Z-score
based on the standard normal distribution (represented byNormalDist()
) for the given confidence using the inverse of the cumulative distribution function (inv_cdf
).Produces the confidence interval based on the sample's standard deviation and mean.
This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z
value.
참고URL : https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data
'program tip' 카테고리의 다른 글
2 개의 객체 배열 병합 (0) | 2020.09.11 |
---|---|
Mac OS X에서 파일을 사용하는 프로세스 확인 (0) | 2020.09.11 |
CSV Python에 몇 줄이 있습니까? (0) | 2020.09.11 |
Android 지원 라이브러리를 23.2.0으로 업데이트하면 오류 발생 : XmlPullParserException 바이너리 XML 파일 줄 # 17 (0) | 2020.09.11 |
홈 디렉토리와 관련된 파일을 여는 방법 (0) | 2020.09.11 |