Python 因果推断
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
import numpy as np
from scipy.stats import norm
# 定义一个函数来生成因果数据
def generate_data(n, beta0, beta1, sigma):
x = np.random.normal(0, 1, n)
y = beta0 + beta1 * x + np.random.normal(0, sigma, n)
return x, y
# 生成数据
n = 1000
x, y = generate_data(n, beta0=1, beta1=2, sigma=0.5)
# 使用statsmodels库进行线性回归分析
import statsmodels.api as sm
X = sm.add_constant(x)
model = sm.OLS(y, X).fit()
print(model.summary())
# 计算置信区间
alpha = 0.05
pred_mean = model.predict(X)
pred_std = np.std(y) * np.sqrt((1.0 + (1.0 / n) + (x - np.mean(x)) ** 2 / np.var(x)) ** 2)
z_score = norm.ppf(1 - alpha / 2)
confidence_interval = z_score * pred_std
print("置信区间:", confidence_interval)
这段代码首先定义了一个函数来生成因果数据,然后使用statsmodels.api
中的OLS
进行线性回归分析,并输出模型的摘要。最后,它计算了预测的标准误差,并打印出置信区间。这个例子展示了如何进行基本的因果推断,包括参数估计和置信区间的计算。
评论已关闭