상세 컨텐츠

본문 제목

[파이썬] 이원분산분석(Two way Anova)을 anova_lm와 OLS로 수행할 수 있을까?

카테고리 없음

by FDG 2024. 5. 6. 01:36

본문

결론부터 말하면 쉽지 않다.

 

anova_lm에 필요한 design_info를 계산해야 하는데, 이거 하다가 포기함.

pasty에 대해서 공부 필요.

 

ols에서 식을 쓰거나

sm.OLS.from_formula를 써서 식을 쓰는 방법이 가장 간편하다!

ols대신 OLS로 해왔었는데, ols가 쓰기 싫으면 sm.OLS.from_formula를 쓰는 게 좋겠다.

anova_lm.ipynb
0.01MB

 

import numpy as np
import pandas as pd
import statsmodels.api as sm
# from statsmodels.formula.api import ols
from statsmodels.stats.anova import anova_lm
from patsy import DesignInfo

np.random.seed(0)
data = {'cat1': np.random.choice([0,1,2,3], 20),
        'cat2': np.random.choice([0,1,2], 20),
        'value': np.random.randint(10, 50, 20)}

df = pd.DataFrame(data)
df.cat1=df.cat1.astype('str')
df.cat2=df.cat2.astype('category')

# 카테고리컬 변수를 더미 변수로 변환
v1 = pd.get_dummies(df['cat1'], prefix='cat1',prefix_sep='[T.', drop_first=True)
v2 = pd.get_dummies(df['cat2'], prefix='cat2',prefix_sep='[T.', drop_first=True)

v1.columns=[i+']' for i in v1.columns]
v2.columns=[i+']' for i in v2.columns]

variables=['Intercept']+[i for i in v1.columns.tolist()]+[i for i in v2.columns.tolist()]
nth_variables=len(variables)

for i in v2:
    for j in v1:
        join_var=j+':'+i
        #print(join_var)
        variables+=[join_var]
print(variables)

X=pd.concat([v1,v2],axis=1)
X.insert(0, variables[0], [1]*len(X))

for i in v2:
    for j in v1:
        X.insert(len(X.columns), variables[nth_variables], X[j]*X[i])
        nth_variables+=1

y=df.value
model = sm.OLS(y, X).fit()
model.model.endog=y

# 이걸 구해야 아노바 분석을 할 수 있는데...

# 구하지 못해서 dmatrices에서 가져왔음

model.model.data.design_info=temp_design_info_for_OLS

result=anova_lm(model)
print(result)

댓글 영역