點選檢視程式碼
import numpy as np
import pandas as pd
import scipy.stats as ss
import statsmodels.api as sm
data = np.loadtxt('F:\python數學建模與演算法\源程式\《Python數學建模演算法與應用》程式和資料\第9章 資料的描述性統計方法/ti9_4.txt')
x1 = np.tile(np.arange(1, 4), (12, 1)).T
x2 = np.tile(np.array([1,1,1,2,2,2,3,3,3,4,4,4]), (3, 1))
model_dic = {'x1': x1.flatten(), 'x2': x2.flatten(), 'y': data.flatten()}
model = sm.formula.ols('y~C(x1)*C(x2)', model_dic).fit()
sm.stats.anova_lm(model)
model = sm.formula.ols('y~C(x1)*C(x2)', model_dic).fit()
print(model.summary()) # 列印模型摘要
anova_result = sm.stats.anova_lm(model)
print(anova_result) # 列印ANOVA結果