方差分析 交互效应和无交互效应

方差分析,二元的,可以分为无交互效应和有交互效应。
代码如下:

import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
plt.style.use("bmh")

import statsmodels.api as sm
from statsmodels.formula.api import ols

ybar = 87.5
alpha = 2.5
beta = 5

A = [1]*10 + [-1]*10
B = [1]*5 + [-1] * 5 +  [1]*5 + [-1] * 5

y = np.array([ybar]*20) +np.array(A) * 2.5 +np.array(B) * 5 + np.random.normal(loc=0, scale=2, size=20)

df = pd.DataFrame({"group1":A, "group2":B, "y":y})
mod = ols("y~group1+group2+group1*group2", data=df).fit()

ano_table = sm.stats.anova_lm(mod)
ano_table

table = pd.pivot_table(df, index=['group1', 'group2'])
table
table2= table.reset_index()

fig, ax = plt.subplots()
y = table2['y']
xall = [1, 2]
ax.plot(xall[0], y[0], 'bo')
ax.plot(xall[0], y[1], 'bo')
ax.plot(xall[1], y[2], 'bo')
ax.plot(xall[1], y[3], 'bo')

ax.plot([1, 2], [y[0], y[2]], 'r')
ax.plot([1, 2], [y[1], y[3]], 'g')

table2
fig, ax = plt.subplots()
ax.plot(1, y[0], 'bo')
ax.plot(1, y[2], 'bo')
ax.plot(2, y[1], 'bo')
ax.plot(2, y[3], 'bo')

ax.plot([1, 2], [y[0], y[1]], 'r')
ax.plot([1, 2],[y[2], y[3]] , 'g')



##########################################
#################有交互作用
##########################################

y = np.array([ybar]*20) +np.array(A) * 2.5 +np.array(B) * 5 + np.array(A) * np.array(B) * 3 + np.random.normal(loc=0, scale=2, size=20)

df = pd.DataFrame({"group1":A, "group2":B, "y":y})
mod = ols("y~group1+group2+group1*group2", data=df).fit()

ano_table = sm.stats.anova_lm(mod)
ano_table

table = pd.pivot_table(df, index=['group1', 'group2'])
table
table2= table.reset_index()

fig, ax = plt.subplots()
y = table2['y']
xall = [1, 2]
ax.plot(xall[0], y[0], 'bo')
ax.plot(xall[0], y[1], 'bo')
ax.plot(xall[1], y[2], 'bo')
ax.plot(xall[1], y[3], 'bo')

ax.plot([1, 2], [y[0], y[2]], 'r')
ax.plot([1, 2], [y[1], y[3]], 'g')

table2
fig, ax = plt.subplots()
ax.plot(1, y[0], 'bo')
ax.plot(1, y[2], 'bo')
ax.plot(2, y[1], 'bo')
ax.plot(2, y[3], 'bo')

ax.plot([1, 2], [y[0], y[1]], 'r')
ax.plot([1, 2],[y[2], y[3]] , 'g')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值