Statistics/Concepts(+codes)

T-test 👉《Two-samples 'independent' T-test (w/python code)》

metamong 2022. 4. 20.

가설검정 hypothesis test에 대해서 배웠고

② 그 중 대표적인 One-sample T-test에 대해서 배웠다.

 

T-test 👉 《One-sample T-test (w/ python code)》

👒 저번 시간에 statistics에서 빼놓을 수 없는 '가설검정 TEST - Hypothesis Test'에 대해 배웠다. Hypothesis Test: H0 & Ha - concepts 1. Hypothesis Testing? → Null Hypothesis(H0) 🙆‍♂️ 1▶ Creat..

sh-avid-learner.tistory.com

👮‍♂️ One-sample T-test를 간단히 얘기하자면, 우리가 모르는 모집단의 평균이 표본집단의 평균과 같은 지(또는 크거나 작은 지)를 알아보는 test였다.

👮‍♂️ 다룰 Two-sampls T-test모집단이 두 개가 있고 각 두 집단의 평균이 같은 지, 같지 않은 지를 '통계적 유의성' 범위 내에서 알아보는 test이다! (여기서 다루는 건 independent t-test)

 

- 아래 그림과 같이 두 정규 모집단이 있다고 가정하자 -

1. 개요

≫ 가정

1> 두 모집단에 추출된 표본들은 서로 독립 (서로 영향을 주는 관계가 아니다)

2> 두 모집단 모두 정규 모집단

3> 두 모집단의 분산이 모두 동일! 등분산 가정

4> 각각 n1, n2개의 표본을 '독립적'으로 추출한다

 

≫ test 진행

👳‍♂️ 두 표본평균의 차이로 모평균의 차이를 추론

→ 모평균 차이를 추정한 추정량의 표본분포가 필요하며, 이 때의 분포는 t분포를 사용

 

≫ 추정량의 t분포 구하기

 

- Sp2는 합동분산추정량 -

 

두 표본집단의 분산 S1과 S2를 적절히 조합해서 Sp(pooled sample variance) 합동분산추정량을 계산한다

자유도에 의거해서 계산

→ S1의 경우 (n1-1)/(n1+n2-2)의 가중치 & S2의 경우 (n2-1)/(n1+n2-2)의 가중치를 갖는다 (두 가중치를 합하면 1)

(S1 집단의 표본 개수는 n1, S2 집단의 표본 개수는 n2)

→ 당연히 두 집단 각각에 동일한 가중치를 부과해서는 안된다, 표본 수가 더 많은 집단쪽이 더 믿을만하기 때문에 표본 수 가 반영된 가중치가 반영되어야 함)

전체의 자유도는 (n1-1) + (n2-1) = n1+n2-2이며, S1의 자유도는 (n1-1), S2의 자유도는 (n2-1)

 

검정통계량 T값을 구하는 식의 '분모'는 '(합동분산추정량)/root(n1+n2)'

 

검정통계량 T값을 구하는 식의 '분자'는 (추정량) - (모집단의 추정량) (여기 test에서 추정량은 차이를 뜻함)

 

≫ hypothesis test

귀무가설) 두 모집단의 평균은 서로 같다

대안가설) 두 모집단의 평균은 서로 같지 않다

 

※ 따라서 위에서 구한 검정통계량 T값이 제시한 귀무가설 H0가 사실인 경우 t분포를 따름

 

가설유형 & 검정통계량 정리

 

 

≫ 유의확률 & 유의수준(significance level 100α)을 이용한 검점

유의확률(p-value) = 귀무가설 H0가 사실일 때, 검정통계량 T의 분포에서의 t0(표본자료로부터 계산된 검정통계량의 값)보다 대립가설 방향으로 더 극단적인 값이 나올 확률

「p-value <= 유의수준α 」이면 H0를 기각하는 걸로 결론을 냄!

 

≫ H0이 기각된다면?

단측검정일 경우 한 집단이 다른 집단보다 평균이 크거나 작다이며, 양측검정일 경우 두 집단의 평균이 다르다 - 이렇게 두 가지의 결론을 내릴 수 있다!

2. 예제

Q. 두 종류의 사료가 우유의 생산량에 미치는 영향의 차이를 조사하기 위하여, 31마리의 젖소를 대상으로 실험하였다. 31마리 중에는 랜덤하게 선택된 16마리에는 한 종류의 사료를 주고, 나머지 15마리에게는 다른 종류의 사료를 준 결과 아래와 같은 자료를 얻었다. 우유 생산량은 정규분포를 따르며, 두 그룹의 분산은 동일하다고 가정할 때, 사료 1을 사용할 경우가 사료 2를 사용할 경우에 비하여 평균 우유 생산량이 많다고 할 수 있는 지(오른꼬리검정) 유의수준 5%에서 검정하여라

 

(사료1: 41, 44, 42, 45, 49, 46, 48, 50, 42, 44, 46, 46, 47, 48, 47, 45)

(사료2: 40, 46, 42, 45, 45, 46, 42, 44, 40, 40, 44, 46, 42, 42, 44)

 

A.

1> 귀무가설

→ '총 31마리의 젖소'를 두 그룹으로 나눈, 두 그룹의 평균 우유 생산량이 같다

 

2> 검정통계량 & 확률분포

→ 귀무가설 H0가 사실일 경우 T분포를 구하고 t0값을 구해본다면

 

- n1,n2는 16,15 / 각 표본평균 45.625, 43.2 / 합동추정분산은 두 표준편차 2.5788, 2.2104를 자유도에 의거, 각각 분배해서 구함 -

 

- 그 결과 t0(검정통계량)는 2.8 - 

 

3> 유의확률 계산

→ 오른꼬리검정(one-sided t-test)이므로 P[T > 2.80] = 0.004476 (위 0.009의 절반)

→ 즉 p-value가 유의수준 0.05보다 작기 때문에 귀무가설은 기각된다

※ 결론 '첫 사료에 의한 우유생산량의 평균이 두 번째 사료에 의한 생산량 평균보다 많다'라고 통계적으로 유의하게 설명할 수 있다.

3. w/python code

▧scipy- two samples t-test docu▧

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html

"Calculate the T-test for the means of two independent samples of scores. This is a test for the null hypothesis that 2 independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default."

 

scipy.stats.ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate', permutations=None, random_state=None, alternative='two-sided', trim=0)

 

a,b - 두 집단

equal_var - True이면 등분산이라 가정하는 'independent 2 sample test'를 시행 / False이면 등분산이 아니라 가정하는 'Welch's t-test' 시행

alternative - Ha 결정방법 - default는 'two-sided' & 'less'이면 a집단이 b집단보다 평균이 작다는 게 Ha / 'greater'이면 b집단의 평균이 작다는 게 Ha로 채택된다

 

! returns (1)t0 검정통계량 값 + (2)p-value

 

👵🏻 docu() two-samples t-test 설명 👵🏻

"Suppose we observe two independent samples, e.g. flower petal lengths, and we are considering whether the two samples were drawn from the same population (e.g. the same species of flower or two species with similar petal characteristics) or two different populations. The t-test quantifies the difference between the arithmetic means of the two samples. The p-value quantifies the probability of observing as or more extreme values assuming the null hypothesis, that the samples are drawn from populations with the same population means, is true. A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that our observation is not so unlikely to have occurred by chance. Therefore, we do not reject the null hypothesis of equal population means. If the p-value is smaller than our threshold, then we have evidence against the null hypothesis of equal population means. By default, the p-value is determined by comparing the t-statistic of the observed data against a theoretical t-distribution. When 1 < permutations < binom(n, k), where

- k is the number of observations in a,

- n is the total number of observations in a and b, and

- binom(n, k) is the binomial coefficient (n choose k),

the data are pooled (concatenated), randomly assigned to either group a or b, and the t-statistic is calculated. This process is performed repeatedly (permutation times), generating a distribution of the t-statistic(t-분포를 생성하기 위해서는 랜덤하게 a와 b 집단에 배정된다)under the null hypothesis, and the t-statistic of the observed data is compared to this distribution to determine the p-value. When permutations >= binom(n, k), an exact test is performed: the data are partitioned between the groups in each distinct way exactly once.

 The permutation test can be computationally expensive and not necessarily more accurate than the analytical test, but it does not make strong assumptions about the shape of the underlying distribution.

 Use of trimming is commonly referred to as the trimmed t-test. At times called Yuen’s t-test, this is an extension of Welch’s t-test, with the difference being the use of winsorized means(중앙집중경향 평균) in calculation of the variance and the trimmed sample size in calculation of the statistic(Yuen's t-test는 주로 끝부분이 길거나, outlier가 있을 때 사용하는 test로 그냥 mean이 아닌 winsorized mean을 사용해 좀 더 정교한 statistical testing을 시행하는 t-test의 일종이다). Trimming is recommended if the underlying distribution is long-tailed or contaminated with outliers"

 

예시>

Q. 서울시 가로수 현황 통계에서 은행나무와 느티나무의 정보를 수집해보자. 은행나무 집단과 느티나무의 집단 두 집단을 전체 은행나무 & 느티나무 모집단에서 sampling 했다고 가정하자. 이 때, 모집단 전체 나무 개수는 정규분포를 따르며, 두 그룹의 분산은 동일하다고 가정할 때, 서울시 은행나무 개수 평균과 느티나무 개수 평균이 같다고 할 수 있는 지(양측검정) 유의수준 5%에서 검정하여라

 

import pandas as pd

trees = pd.read_csv('https://ds-lecture-data.s3.ap-northeast-2.amazonaws.com/seoul_tree/seoul_tree.txt', sep = '\t', skiprows = 1)
trees = trees.replace({'-':0})

tree1 = pd.to_numeric(trees['은행나무'].str.replace(',','')) # 은행나무 데이터
tree2 = pd.to_numeric(trees['느티나무'].str.replace(',','')) # 느티나무 데이터

print(np.mean(tree1)) #7717
print(np.mean(tree2)) #2677

 

≫ 직접 평균을 비교해본 결과 두 집단간의 평균은 각각 7717, 2677이다. 이제 이 수치를 통계적인 범위에서 t-test의 가정이 적용된다고 생각할 때, 어떻게 결론을 내리는 지 확인해보자

 

stats.ttest_ind(tree1,tree2)
#Ttest_indResult(statistic=1.2730451277184196, pvalue=0.20845547747699233)

 

pvalue가 0.05값을 넘는다. 따라서 H0으로 귀무가설 세운 '은행나무와 느티나무 개수의 평균은 차이가 없다'가 기각되지 않으므로, 우리는 두 나무 개수의 평균은 차이가 없다라고는 통계적 유의성 범위 내에서 말할 수 없다고 할 수 있다!


* 썸넬) https://kennethrfaro.com/capabilities

* 출처1) (winsorized mean) https://www.investopedia.com/terms/w/winsorized_mean.asp

* 출처2) ProDS 

댓글