You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中执行Wald检验?特定假设检验的代码疑问

Answer

Great question! You're already on the right track using statsmodels' OLS implementation—here's how to run those Wald tests correctly with the wald_test() method built into the fitted results object:

Full Working Code

from statsmodels.datasets import longley
import statsmodels.formula.api as smf

# Load the sample data
data = longley.load_pandas().data

# Define your hypotheses (including your target: Intercept=0, GNP=1)
hypothesis_0 = '(Intercept = 0, GNP = 0)'
hypothesis_1 = '(GNP = 0)'
hypothesis_2 = '(GNP = 1)'
hypothesis_3 = '(Intercept = 0, GNP = 1)'  # Your key hypothesis

# Fit the OLS regression model
results = smf.ols('TOTEMP ~ GNP', data).fit()

# Execute each Wald test
wald_0 = results.wald_test(hypothesis_0)
wald_1 = results.wald_test(hypothesis_1)
wald_2 = results.wald_test(hypothesis_2)
wald_3 = results.wald_test(hypothesis_3)  # This is the test you need

# Print the result for your target hypothesis
print("Wald Test Results: Intercept = 0 and GNP coefficient = 1")
print(wald_3)

How It Works

  • The wald_test() method accepts a string defining your null hypothesis using the exact variable names from your model (here, Intercept and GNP). For multiple constraints, separate them with commas inside the parentheses.
  • The output will include:
    • A chi-squared test statistic
    • Degrees of freedom (equal to the number of constraints in your hypothesis—2 for hypothesis_3)
    • A p-value

Interpreting the Result

  • If the p-value is greater than your chosen significance level (e.g., 0.05), you fail to reject the null hypothesis that Intercept=0 and GNP=1.
  • If the p-value is less than your significance level, you reject the null hypothesis.

Bonus: Custom Contrast Matrix (Optional)

For more complex hypotheses, you can pass a contrast matrix instead of a string. For your target hypothesis, the matrix would look like this:

import numpy as np
contrast_matrix = np.array([[1, 0],  # Intercept = 0
                            [0, 1]]) # GNP = 1
wald_3_matrix = results.wald_test(contrast_matrix, value=[0, 1])
print(wald_3_matrix)

This gives the exact same result as the string method, but is useful for non-linear or more complex constraints.

内容的提问来源于stack exchange,提问作者파워뿡뿡이

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:03:46