import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# 生成模擬數(shù)據(jù)(假設(shè)每組有30個(gè)樣本)
np.random.seed(0)
fertilizer_a = np.random.normal(20, 5, 30) # 肥料A組的植物高度
fertilizer_b = np.random.normal(22, 5, 30) # 肥料B組的植物高度
fertilizer_c = np.random.normal(23, 5, 30) # 肥料C組的植物高度
# 單因素方差分析
f_value, p_value = stats.f_oneway(fertilizer_a, fertilizer_b, fertilizer_c)
print(f"F值: {f_value}")
print(f"p值: {p_value}")
# 創(chuàng)建一個(gè)包含所有組的 DataFrame
data = {
'height': np.concatenate([fertilizer_a, fertilizer_b, fertilizer_c]),
'fertilizer': ['Fertilizer A']*len(fertilizer_a) +
['Fertilizer B']*len(fertilizer_b) +
['Fertilizer C']*len(fertilizer_c)
}
df = pd.DataFrame(data)
# 使用 seaborn 進(jìn)行可視化
plt.figure(figsize=(10, 6))
sns.boxplot(x='fertilizer', y='height', data=df)
sns.swarmplot(x='fertilizer', y='height', data=df, color='black', alpha=0.5)
plt.title('Effect of Different Fertilizers on Plant Growth')
plt.xlabel('Fertilizer Type')
plt.ylabel('Plant Height (cm)')
plt.show()

結(jié)果解讀

使用np.random.normal生成模擬數(shù)據(jù),假設(shè)每組植物的高度符合正態(tài)分布,但均值不同(分別為20、22和23),標(biāo)準(zhǔn)差相同(5),利用箱圖展示不同肥料對(duì)植物生長(zhǎng)的影響,這里??值大于顯著性水平(通常為0.05),則認(rèn)為不同肥料類(lèi)型對(duì)植物生長(zhǎng)的影響不顯著

單因素方差分析實(shí)現(xiàn)

代碼

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from statsmodels.formula.api import ols
# 生成模擬數(shù)據(jù)
np.random.seed(0)
num_samples = 15
fertilizer_types = ['Fertilizer A', 'Fertilizer B', 'Fertilizer C']
watering_frequencies = ['Daily', 'Weekly']
data = []
for fertilizer in fertilizer_types:
for watering in watering_frequencies:
# 隨機(jī)生成植物高度數(shù)據(jù)
heights = np.random.normal(loc=20 + 2 * fertilizer_types.index(fertilizer) + 5 * (watering == 'Daily'), scale=5, size=num_samples)
for height in heights:
data.append([fertilizer, watering, height])
# 創(chuàng)建 DataFrame
df = pd.DataFrame(data, columns=['Fertilizer', 'Watering', 'Height'])
# 雙因素方差分析
model = ols('Height ~ C(Fertilizer) * C(Watering)', data=df).fit()
anova_table = sm.stats.anova_lm(model, typ=2)
print(anova_table)
# 使用 seaborn 進(jìn)行可視化
plt.figure(figsize=(15, 5))
plt.subplot(1,2,1)
# 交互作用圖
interaction_plot = sns.pointplot(x='Fertilizer', y='Height', hue='Watering', data=df, markers=["o", "s"], linestyles=["-", "--"])
plt.title('Interaction Plot of Fertilizer Type and Watering Frequency on Plant Height')
plt.xlabel('Fertilizer Type')
plt.ylabel('Plant Height (cm)')
plt.legend(title='Watering Frequency')
plt.subplot(1,2,2)
# 箱線圖
sns.boxplot(x='Fertilizer', y='Height', hue='Watering', data=df)
plt.title('Box Plot of Plant Height by Fertilizer Type and Watering Frequency')
plt.xlabel('Fertilizer Type')
plt.ylabel('Plant Height (cm)')
plt.legend(title='Watering Frequency')
plt.show()

背景

研究問(wèn)題

假設(shè)研究不同類(lèi)型的肥料和不同的灌溉頻率對(duì)植物生長(zhǎng)的影響是否顯著?是否存在交互效應(yīng)?

實(shí)驗(yàn)設(shè)計(jì)

結(jié)果解讀
使用statsmodels庫(kù)中的ols函數(shù)進(jìn)行線性回歸模型擬合,并使用anova_lm進(jìn)行雙因素方差分析,輸出的ANOVA表格顯示了各個(gè)因素(肥料類(lèi)型、灌溉頻率)及其交互作用對(duì)植物高度的影響,通過(guò)交互作用圖,可以直觀地看到不同肥料類(lèi)型和灌溉頻率的組合對(duì)植物高度的影響,箱線圖展示了每種組合下植物高度的分布和離群值,便于比較不同組之間的差異,接下來(lái)我們對(duì)ANOVA表格進(jìn)行詳細(xì)的解讀:

根據(jù)這些結(jié)果,我們可以建議關(guān)注灌溉頻率對(duì)植物生長(zhǎng)的顯著影響,而肥料類(lèi)型和其與灌溉頻率的交互作用在本次實(shí)驗(yàn)中沒(méi)有顯著影響結(jié)束語(yǔ)通過(guò)本次對(duì)單因素方差分析和雙因素方差分析的介紹及實(shí)踐,了解如何利用統(tǒng)計(jì)方法評(píng)估不同因素及其交互作用對(duì)實(shí)驗(yàn)結(jié)果的影響,其實(shí)在機(jī)器學(xué)習(xí)上也會(huì)引入方差分析進(jìn)行特征選擇參考文章特征篩選(過(guò)濾法)—— ANOVA?,這樣的方法幫助我們理解哪些特征對(duì)目標(biāo)變量有顯著影響,從而優(yōu)化模型性能

本文章轉(zhuǎn)載微信公眾號(hào)@Python機(jī)器學(xué)習(xí)AI

上一篇:

Python實(shí)現(xiàn)數(shù)據(jù)預(yù)處理:常見(jiàn)缺失值處理方法解析

下一篇:

時(shí)間序列預(yù)測(cè)神器Prophet python實(shí)現(xiàn)

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)