9.2 9.3 9.4 9.5

zzzhhhhha發表於2024-12-10

9.2

點選檢視程式碼
import numpy as np
from scipy.stats import shapiro

data = [15.0, 15.8, 15.2, 15.1, 15.9, 14.7, 14.8, 15.5, 15.6, 15.3,
15.1, 15.3, 15.0, 15.6, 15.7, 14.8, 14.5, 14.2, 14.9, 14.9,
15.2, 15.0, 15.3, 15.6, 15.1, 14.9, 14.2, 14.6, 15.8, 15.2,
15.9, 15.2, 15.0, 14.9, 14.8, 14.5, 15.1, 15.5, 15.5, 15.1,
15.1, 15.0, 15.3, 14.7, 14.5, 15.5, 15.0, 14.7, 14.6, 14.2]

stat, p = shapiro(data)

print(f"Shapiro-Wilk Statistic: {stat}")
print(f"P-value: {p}")

alpha = 0.05
if p > alpha:
    print("滾珠直徑資料服從正態分佈N(15.0780, 0.4325^2)。")
else:
    print("滾珠直徑資料不服從正態分佈N(15.0780, 0.4325^2)。")

print("3010")

9.3

點選檢視程式碼
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
 
# 建立資料
X = np.array([
    4.13, 4.07, 4.04, 4.07, 4.05, 4.04, 4.02, 4.06, 4.10, 4.04,
    3.86, 3.85, 4.08, 4.11, 4.08, 4.01, 4.02, 4.04, 3.97, 3.95,
    4.00, 4.02, 4.01, 4.01, 4.04, 3.99, 4.03, 3.97, 3.98, 3.98,
    3.88, 3.88, 3.91, 3.95, 3.92, 3.97, 3.92, 3.90, 3.97, 3.90,
    4.02, 3.95, 4.02, 3.89, 3.91, 4.01, 3.89, 3.89, 3.99, 4.00,
    4.02, 3.86, 3.96, 3.97, 4.00, 3.82, 3.98, 3.99, 4.02, 3.93,
    4.00, 4.02, 4.03, 4.04, 4.10, 3.81, 3.91, 3.96, 4.05, 4.06
])
 
# 建立因子A
A = np.repeat(np.arange(1, 8), 10)
 
# 建立DataFrame
contents = pd.DataFrame({'X': X, 'A': A})
 
# 進行ANOVA分析
aov_cont = stats.f_oneway(*[contents[contents['A'] == i]['X'] for i in range(1, 8)])
print(f"F-statistic: {aov_cont.statistic}, p-value: {aov_cont.pvalue}")
 
# 繪製箱線圖
plt.boxplot([contents[contents['A'] == i]['X'] for i in range(1, 8)], labels=[f'Group {i}' for i in range(1, 8)])
plt.title('Boxplot of X by Group A')
plt.xlabel('Group A')
plt.ylabel('X')
plt.show()
print("3010")

9.4

點選檢視程式碼
import numpy as np
import statsmodels.api as sm
y = np.loadtxt('ti9_4.txt').flatten() #把表中的逗號替換為空格
x1=np.tile(np.arange(1,4),(12,1)).T.flatten()
x2=np.tile(np.hstack([np.ones(3),2*np.ones(3),3*np.ones(3),4*np.ones(3)]),(3,1)).flatten()
d = {'x1':x1,'x2':x2,'y':y}
md=sm.formula.ols('y~C(x1) * C(x2)',d).fit()
ano=sm.stats.anova_lm(md)
print(ano);
print('總偏差平方和:',sum(ano.sum_sq))

9.5

點選檢視程式碼
import numpy as np
import statsmodels.api as sm
y = np.loadtxt('ti9_5.txt').T.flatten()
x1=np.tile(np.hstack([np.ones(4),2*np.ones(4),3*np.ones(4)]),(4,1)).flatten()
x2=np.tile(np.tile([1,1,2,2],(1,3)),(4,1)).flatten()
x3=np.tile(np.tile([1,2],(1,6)),(4,1)).flatten()
d ={'x1':x1,'x2':x2,'x3':x3,"y":y}
md = sm.formula.ols('y~C(x1)*C(x2)*C(x3)',d).fit()
ano=sm.stats.anova_lm(md)
print(ano)
print('總偏差平方和:',sum(ano.sum_sq))
print('3010')

相關文章