匯入路徑與結構

我們提供兩種從 statsmodels 匯入函式和類別的方式

  1. 互動式使用的 API 匯入

    • 允許 Tab 鍵自動完成

  2. 程式的直接匯入

    • 避免匯入不必要的模組和命令

互動式使用的 API 匯入

對於互動式使用,建議的匯入方式是

import statsmodels.api as sm

匯入 statsmodels.api 將會載入 statsmodels 的大部分公開部分。這使得大多數函式和類別在一個或兩個層級內方便地使用,而不會使 "sm" 命名空間過於擁擠。

要查看可用的函式和類別,您可以輸入以下內容(或使用 IPython、Spyder、IDLE 等的命名空間瀏覽功能)

>>> dir(sm)
['GLM', 'GLS', 'GLSAR', 'Logit', 'MNLogit', 'OLS', 'Poisson', 'Probit', 'RLM',
'WLS', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
'add_constant', 'categorical', 'datasets', 'distributions', 'families',
'graphics', 'iolib', 'nonparametric', 'qqplot', 'regression', 'robust',
'stats', 'test', 'tools', 'tsa', 'version']

>>> dir(sm.graphics)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'abline_plot', 'beanplot', 'fboxplot', 'interaction_plot', 'qqplot',
'rainbow', 'rainbowplot', 'violinplot']

>>> dir(sm.tsa)
['AR', 'ARMA', 'SVAR', 'VAR', '__builtins__', '__doc__',
'__file__', '__name__', '__package__', 'acf', 'acovf', 'add_lag',
'add_trend', 'adfuller', 'ccf', 'ccovf', 'datetools', 'detrend',
'filters', 'grangercausalitytests', 'interp', 'lagmat', 'lagmat2ds', 'kpss',
'pacf', 'pacf_ols', 'pacf_yw', 'periodogram', 'q_stat', 'range_unit_root_test',
'stattools', 'tsatools', 'var']

注意事項

api 模組可能不包含 statsmodels 的所有公開功能。如果您發現有應該新增到 api 的內容,請在 github 上提交 issue 或向郵件列表報告。

statsmodels 的子套件包含 api.py 模組,這些模組的主要目的是收集這些子套件所需的匯入。例如,subpackage/api.py 檔案會被匯入到 statsmodels api 中

from .nonparametric import api as nonparametric

使用者不需要直接載入 subpackage/api.py 模組。

程式的直接匯入

statsmodels 子模組是按主題排列的 (例如,discrete 用於離散選擇模型,或 tsa 用於時間序列分析)。我們的目錄樹 (精簡後) 如下所示

statsmodels/
    __init__.py
    api.py
    discrete/
        __init__.py
        discrete_model.py
        tests/
            results/
    tsa/
        __init__.py
        api.py
        tsatools.py
        stattools.py
        arima_process.py
        vector_ar/
            __init__.py
            var_model.py
            tests/
                results/
        tests/
            results/
    stats/
        __init__.py
        api.py
        stattools.py
        tests/
    tools/
        __init__.py
        tools.py
        decorators.py
        tests/

可以大量匯入的子模組包含一個空的 __init__.py,除了用於運行子模組測試的一些測試程式碼之外。目的是在下一個版本中將所有目錄更改為具有 api.py 和空的 __init__.py

匯入範例

函式和類別

from statsmodels.regression.linear_model import OLS, WLS
from statsmodels.tools.tools import rank, add_constant

模組

from statsmodels.datasets import macrodata
import statsmodels.stats import diagnostic

帶有別名的模組

import statsmodels.regression.linear_model as lm
import statsmodels.stats.diagnostic as smsdia
import statsmodels.stats.outliers_influence as oi

我們目前沒有子模組別名的慣例。


上次更新:2024 年 10 月 03 日