当前位置: 首页 > news >正文

ML4T - 第7章第7节 逻辑回归拟合宏观数据Logistic Regression with Macro Data

目录

一、Load Data 加载数据

1.数据解释

2.代码

二、Data Prep 数据处理

三、Fit Model 拟合模型

四、Analyze 结果分析


一、Load Data 加载数据

1.数据解释

VariableDescriptionTransformation
realgdpReal gross domestic product(实际国内生产总值)Annual Growth Rate(年增长率)
realconsReal personal consumption expenditures(实际个人消费支出)Annual Growth Rate(年增长率)
realinvReal gross private domestic investment(实际私人国内总投资)Annual Growth Rate(年增长率)
realgovtReal federal expenditures & gross investment(实际联邦政府支出与总投资)Annual Growth Rate(年增长率)
realdpiReal private disposable income(实际私人可支配收入)Annual Growth Rate(年增长率)
m1M1 nominal money stock(名义M1货币供应量)Annual Growth Rate(年增长率)
tbilrateMonthly treasury bill rate(月度国库券利率)Level(水平值)
unempSeasonally adjusted unemployment rate (%)(季调失业率,单位:%)Level(水平值)
inflInflation rate(通货膨胀率)Level(水平值)
realintReal interest rate(实际利率)Level(水平值)

通过

import statsmodels.api as sm

data = pd.DataFrame(sm.datasets.macrodata.load().data)

下载宏观数据,这里应该指的是美国的

2.代码

%matplotlib inline
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as snssns.set_style('whitegrid')data = pd.DataFrame(sm.datasets.macrodata.load().data)
data.info()data.head()

   结果:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 203 entries, 0 to 202
Data columns (total 14 columns):#   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  0   year      203 non-null    float641   quarter   203 non-null    float642   realgdp   203 non-null    float643   realcons  203 non-null    float644   realinv   203 non-null    float645   realgovt  203 non-null    float646   realdpi   203 non-null    float647   cpi       203 non-null    float648   m1        203 non-null    float649   tbilrate  203 non-null    float6410  unemp     203 non-null    float6411  pop       203 non-null    float6412  infl      203 non-null    float6413  realint   203 non-null    float64
dtypes: float64(14)
memory usage: 22.3 KB

数据格式:

二、Data Prep 数据处理

为了获得一个二元目标变量,我们计算季度实际GDP年增长率的20个季度滚动平均值。然后,如果当前增长超过移动平均值,我们将其分配为1,否则分配为0。最后,我们移动指标变量,使下一季度的结果与当前季度对齐。

To obtain a binary target variable, we compute the 20-quarter rolling average of the annual growth rate of quarterly real GDP. We then assign 1 if current growth exceeds the moving average and 0 otherwise. Finally, we shift the indicator variables to align next quarter's outcome with the current quarter.

data['growth_rate'] = data.realgdp.pct_change(4)
data['target'] = (data.growth_rate > data.growth_rate.rolling(20).mean()).astype(int).shift(-1)
data.quarter = data.quarter.astype(int)data.target.value_counts()data.tail()

pct_cols = ['realcons', 'realinv', 'realgovt', 'realdpi', 'm1']
drop_cols = ['year', 'realgdp', 'pop', 'cpi', 'growth_rate']
data.loc[:, pct_cols] = data.loc[:, pct_cols].pct_change(4)data = pd.get_dummies(data.drop(drop_cols, axis=1), columns=['quarter'], drop_first=True).dropna()data.info()data.head()
<class 'pandas.core.frame.DataFrame'>
Index: 198 entries, 4 to 201
Data columns (total 13 columns):#   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  0   realcons   198 non-null    float641   realinv    198 non-null    float642   realgovt   198 non-null    float643   realdpi    198 non-null    float644   m1         198 non-null    float645   tbilrate   198 non-null    float646   unemp      198 non-null    float647   infl       198 non-null    float648   realint    198 non-null    float649   target     198 non-null    float6410  quarter_2  198 non-null    bool   11  quarter_3  198 non-null    bool   12  quarter_4  198 non-null    bool   
dtypes: bool(3), float64(10)
memory usage: 17.6 KB

三、Fit Model 拟合模型

# model = sm.Logit(data.target, sm.add_constant(data.drop('target', axis=1)))  # bad code
model = sm.Logit(data.target, sm.add_constant(data.drop('target', axis=1).astype(float)))
result = model.fit()
result.summary()

注意,原作者代码已经失效,要加上数据转换才行

# model = sm.Logit(data.target, sm.add_constant(data.drop('target', axis=1))) # bad code

model = sm.Logit(data.target, sm.add_constant(data.drop('target', axis=1).astype(float)))

结果:

Optimization terminated successfully. Current function value: 0.342965 Iterations 8

Logit Regression Results
Dep. Variable:targetNo. Observations:198
Model:LogitDf Residuals:185
Method:MLEDf Model:12
Date:Wed, 01 Oct 2025Pseudo R-squ.:0.5022
Time:11:27:45Log-Likelihood:-67.907
converged:TrueLL-Null:-136.42
Covariance Type:nonrobustLLR p-value:2.375e-23
coefstd errzP>|z|[0.0250.975]
const-8.58811.908-4.5020.000-12.327-4.849
realcons130.144626.6334.8870.00077.945182.344
realinv18.84144.0534.6480.00010.89726.786
realgovt-19.03186.010-3.1660.002-30.812-7.252
realdpi-52.247319.912-2.6240.009-91.275-13.220
m1-1.34626.177-0.2180.827-13.45310.761
tbilrate60.860744.3501.3720.170-26.063147.784
unemp0.94870.2493.8180.0000.4621.436
infl-60.964744.362-1.3740.169-147.91325.984
realint-61.045344.359-1.3760.169-147.98725.896
quarter_20.11280.6180.1820.855-1.0991.325
quarter_3-0.19910.609-0.3270.744-1.3930.995
quarter_40.00070.6080.0010.999-1.1911.192

四、Analyze 结果分析

McFadden Pseudo R² = 0.50, 模型效果还不错。

我们使用截距并将季度值转换为虚拟变量,并按照以下方式训练逻辑回归模型:

这为我们的模型生成了以下摘要,该模型有198个观测值和13个变量(注:12个变量+截距=13),包括截距

摘要表明,该模型已使用最大似然法进行训练,并提供对数似然函数在-67.9处的最大值。

We use an intercept and convert the quarter values to dummy variables and train the logistic regression model as follows:

This produces the following summary for our model with 198 observations and 13 variables, including intercept: The summary indicates that the model has been trained using maximum likelihood and provides the maximized value of the log-likelihood function at -67.9.

plt.rc('figure', figsize=(12, 7))
plt.text(0.01, 0.05, str(result.summary()), {'fontsize': 14}, fontproperties = 'monospace')
plt.axis('off')
plt.tight_layout()
plt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.1)
plt.savefig('logistic_example.png', bbox_inches='tight', dpi=300);

http://www.dtcms.com/a/431117.html

相关文章:

  • 宿州学校网站建设东营城乡建设局官网
  • 从通用人工智能(AGI)到超级智能(ASI):演化、挑战与启示
  • CycloneDX:全栈软件供应链安全标准解读及优势分析
  • Python 线程同步原语大全:Lock、RLock、Semaphore、Condition、Event实战
  • 青岛网站建设在哪温州高端网站定制
  • keil5添加其他芯片包pack文件的方式
  • 短剧小程序跨端适配实战:UniApp / 原生开发选型与多终端体验一致性保障
  • 第四周作业(包括小组网页设计-对Bootstrap的初步了解)
  • 算法时空博弈:效率与资源的交响诗篇
  • TensorFlow与PyTorch深度对比分析:从基础原理到实战选择的完整指南
  • 图像分类模型 传统训练VS迁移学习训练
  • 专业的东莞网站设计免费制作永久个人网站
  • 【数据结构与算法学习笔记】队列
  • Service Worker:前端离线化与性能优化的核心技术
  • FFmpeg 深入精讲(五)播放器核心技术
  • 迪拜哪个网站是做网站的网络平台有哪些?
  • 【天池经典打榜赛】赛道四-知识图谱预测赛的代码文档
  • typescript 中 for..of 和 for..in的区别
  • 安卓和网站开发找工作wordpress 改网站域名
  • AI 提效:利用 AI 从前端 快速转型为UI/UX设计师和产品
  • 模板网站建站公司公主岭网站建设
  • DAY 37 早停策略和模型权重的保存-2025.10.1
  • 百联网上购物商城南昌百度推广优化排名
  • DataHub:一个现代化的元数据管理平台
  • 做 58 那样的网站wordpress图片外链
  • 腾讯开源 Hunyuan-MT-7B:33语种全覆盖、30项WMT25冠军的轻量级机器翻译新标杆
  • 郑州网站APP网站推广做多大尺寸
  • node.js 二进制安装
  • 【办公类-116-01】20250929家长会PPT(Python快速批量制作16:9PPT相册,带文件名,照片横版和竖版)
  • 鸿蒙应用Hello World