PyMC3 API 解讀(二)—— sample() 函數

特此聲明:本博文爲我的另一片博文 PyMC3 概率編程入門 的從博文,之前屬於其中的一部分內容,但是因爲該篇主博文內容較多,整體比較繁雜,閱讀體驗感較差,並且今後對該主博文會做更新,將其作爲學習筆記。因此出於學習目的,我決定將主博文定位爲入門 PyMC3 概率編程的學習脈絡與框架部分,而將其中的細節於諸多從博文中展示,這樣既符合模塊化思維,又提升主博文的閱讀體驗,以防自己和觀看的同學們在繁雜的內容中找不到重點。因爲該篇博文是從博文,所以會和主博文有一定的聯繫,不過我會盡量將知識點獨立地剝離出來,如果大家有什麼不清楚的地方,請在評論區提出,我會盡快修改,有興趣的同學可以移步至主博文閱讀一下。

sample() 函數

通過本篇博文我們來了解一下 sample() 函數,這個函數的參數比較多,接下來對這些參數一個一個來解釋,幫助大家弄清楚它們分別代表什麼意思:

def sample(draws=500, step=None, init="auto", n_init=200000, start=None, trace=None, 
	chain_idx=0, chains=None, cores=None, tune=500, progressbar=True, model=None, 
	random_seed=None, discard_tuned_samples=True, compute_convergence_checks=True, 
	**kwargs)
  • drawsint 類型,表示通過 MCMC 方法採樣出的正式樣本的數量,默認爲 500,這裏的正式樣本是相對於預燒期樣本來說的,預燒期的樣本數量對應參數 tune,等下也會解釋它,這裏舉個例子,假如將 draws=5000, tune=1000 傳入 sample() 函數,那麼對於一條 MCMC 鏈來說,前面 1000 個採樣出來的樣本不算進正式的採樣樣本,而後 5000 個採樣出來的樣本(1001 ~ 6000)纔是正式採樣的樣本;

  • stepBlockedStep 類的子類的實例化對象類型,表示所選擇的 MCMC 採樣算法(step method),PyMC3 中提供了內置的採樣算法,比如 NUTS、Metropolis、Slice、HamiltonianMC 和 BinaryMetropolis 等,採樣算法可以由 PyMC3 自動指定也可以手動進行指定,自動指定是根據模型中的變量類型決定的,手動指定優先,可覆蓋自動指定,如下爲自動指定的採樣算法:

    1. 二值變量:自動指定 BinaryMetropolis 採樣算法
    2. 離散變量:自動指定 Metropolis 採樣算法
    3. 連續變量:自動指定 NUTS 採樣算法

    概念大家大概瞭解就行,我們來舉個例子,看看怎麼使用這個參數,假如現在我有 alphabetasigma 三個參數,而我想要對我的參數 alpha 使用 Slice 採樣算法進行採樣,那麼我們可以實例化一個 Slice 類的對象,然後將該實例對象傳給 step,可以看到在進度條顯示出模型使用 Slice 採樣算法對 alpha 進行採樣,而因爲我沒有指定對 betasigma 使用什麼採樣算法,所以模型會自動默認使用 NUTS 採樣算法對它們進行採樣:
    在這裏插入圖片描述
    那假如對 betasigma 兩個參數我也想自己指定所使用的採用算法,那我可以這樣做,分別使用 Slice 類、Metropolis 類 和 NUTS 類實例化對象,然後將這個實例對象組成列表傳給 step
    在這裏插入圖片描述

  • init:str 類型,表示使用 NUTS 採樣算法時所使用的的初始化方法,默認爲 “auto” 即自動選擇一個較好的初始化方法;

  • n_init:int 類型,表示初始化的迭代次數,默認爲 200000,僅在 init 參數爲 “nuts” 或 “advi” 時有效;

  • startdict 類型,表示 MCMC 採樣時參數的初始值的字典,默認是模型自帶的測試點,一般以 start={'alpha':1, 'beta':2, 'theta':3} 的形式進行傳參,實際上,我們很多時候都先使用 find_MAP() 函數來計算參數的極大似然點估計值,然後將該點估計值作爲採樣時參數的初始值,關於 find_MAP() 函數的具體內容大家可以參照:PyMC3 API 解讀(一)—— find_MAP() 函數
    在這裏插入圖片描述

  • trace:list 類型,表示模型在後臺要跟蹤的變量;

  • chain_idxint 類型,表示 MCMC 鏈存儲在後臺的編號的起始值,默認爲 0,比如說如果我的參數設置爲 chain_idx=1, chains=4,那麼就會產生四條獨立的 MCMC 鏈,且它們存儲在後臺的編號分別爲 1, 2, 3, 4,而不是 0, 1, 2, 3;

  • chainsint 類型,表示採樣時生成的 MCMC 鏈的數量,並且這些鏈是相互獨立的,如果被設置爲 None 也就是不顯式地傳入參數給 chains,那麼就在 cores 參數和 2 之間選一個更大的數作爲參數值傳給 chains

  • coresint 類型,表示並行運行的鏈的數量,如果被設置爲 None 也就是不顯式地傳入參數給 cores,那麼就將當前主機的 CPU 的個數作爲參數值傳給 cores,不過參數值最大不超過 4;

  • tuneint 類型,表示調參過程的迭代輪數,默認爲 500,其實這就是預燒期的樣本的數量,所謂預燒期就是我們在產生 MCMC 鏈的時候,前面採樣出的一部分樣本可能不是平穩分佈的 MCMC 鏈所產生的,而後面的由平穩分佈的 MCMC 鏈產生的採樣樣本纔是我們真正想要的,因此我們常常會丟棄預燒期的樣本,不過在 sample() 函數當中是否丟棄預燒期樣本由參數 discard_tuned_samples 決定;

  • progressbar:bool 類型,表示是否在命令行中顯示程序運行時的進度條;

  • modelModel 類型,表示當前的模型,如果 find_MAP() 函數是在 with pm.Model() 上下文管理器中,那這個參數就不用指定,如果不在則需要指定,否則會報錯;

  • random_seed:int 類型,表示設置的隨機數種子;

  • discard_tuned_samplesbool 類型,表示是否丟棄預燒期樣本,默認爲 True,則最後返回的採樣樣本數不包括預燒期的樣本數即丟棄預燒期的樣本,以之前的例子來講,假如將 draws=5000, tune=1000 傳入 sample() 函數,然後將 discard_tuned_samples 分別設置爲 True 和 False,我們來分別觀察它們的不同點:
    在這裏插入圖片描述
    我們可以看到它們在進度條顯示的內容相差不多,那我們打印一下它們採樣的結果,我們會發現,當 discard_tuned_samples 設置爲 True 時,最終採樣出 20000 個樣本,設置爲 False 時,最終採樣出 24000 個樣本,這是因爲我們一次採樣過程會產生 4 條獨立的 MCMC 鏈,所以如果丟棄 tune=1000 個預燒期樣本就是 5000 * 4 = 20000,而將預燒期樣本保留下來就是 (5000 + 1000) * 4 = 24000:
    在這裏插入圖片描述

  • compute_convergence_checks:bool 類型,表示是否計算樣本的數據統計,默認爲 True;

  • **kwargs:還未探究。

:上述衆多參數中使用粗體表示的是我基本探究清楚的,而未使用粗體表示的是還沒有探究清楚的和還未探究的。

sample() 函數的返回值是一個 pymc3.backends.base.MultiTrace 類的對象,大家可以把它當作字典來用,如下:
在這裏插入圖片描述
關於 sample() 函數,下面也給出了它在源碼中的說明和參數解釋,大家可以參考一下:

def sample(draws=500, step=None, init="auto", n_init=200000, start=None, trace=None, 
	chain_idx=0, chains=None, cores=None, tune=500, progressbar=True, model=None, 
	random_seed=None, discard_tuned_samples=True, compute_convergence_checks=True, 
	**kwargs)
    """
    Draw samples from the posterior using the given step methods.

    Multiple step methods are supported via compound step methods.

    Parameters
    ----------
    draws : int
        The number of samples to draw. Defaults to 500. The number of tuned samples are discarded
        by default. See ``discard_tuned_samples``.
    step : function or iterable of functions
        A step function or collection of functions. If there are variables without step methods,
        step methods for those variables will be assigned automatically.  By default the NUTS step
        method will be used, if appropriate to the model; this is a good default for beginning
        users.
    init : str
        Initialization method to use for auto-assigned NUTS samplers.

        * auto : Choose a default initialization method automatically.
          Currently, this is ``'jitter+adapt_diag'``, but this can change in the future.
          If you depend on the exact behaviour, choose an initialization method explicitly.
        * adapt_diag : Start with a identity mass matrix and then adapt a diagonal based on the
          variance of the tuning samples. All chains use the test value (usually the prior mean)
          as starting point.
        * jitter+adapt_diag : Same as ``adapt_diag``\, but add uniform jitter in [-1, 1] to the
          starting point in each chain.
        * advi+adapt_diag : Run ADVI and then adapt the resulting diagonal mass matrix based on the
          sample variance of the tuning samples.
        * advi+adapt_diag_grad : Run ADVI and then adapt the resulting diagonal mass matrix based
          on the variance of the gradients during tuning. This is **experimental** and might be
          removed in a future release.
        * advi : Run ADVI to estimate posterior mean and diagonal mass matrix.
        * advi_map: Initialize ADVI with MAP and use MAP as starting point.
        * map : Use the MAP as starting point. This is discouraged.
        * nuts : Run NUTS and estimate posterior mean and mass matrix from the trace.
    n_init : int
        Number of iterations of initializer. Only works for 'nuts' and 'ADVI'.
        If 'ADVI', number of iterations, if 'nuts', number of draws.
    start : dict, or array of dict
        Starting point in parameter space (or partial point)
        Defaults to ``trace.point(-1))`` if there is a trace provided and model.test_point if not
        (defaults to empty dict). Initialization methods for NUTS (see ``init`` keyword) can
        overwrite the default.
    trace : backend, list, or MultiTrace
        This should be a backend instance, a list of variables to track, or a MultiTrace object
        with past values. If a MultiTrace object is given, it must contain samples for the chain
        number ``chain``. If None or a list of variables, the NDArray backend is used.
        Passing either "text" or "sqlite" is taken as a shortcut to set up the corresponding
        backend (with "mcmc" used as the base name).
    chain_idx : int
        Chain number used to store sample in backend. If ``chains`` is greater than one, chain
        numbers will start here.
    chains : int
        The number of chains to sample. Running independent chains is important for some
        convergence statistics and can also reveal multiple modes in the posterior. If ``None``,
        then set to either ``cores`` or 2, whichever is larger.
    cores : int
        The number of chains to run in parallel. If ``None``, set to the number of CPUs in the
        system, but at most 4.
    tune : int
        Number of iterations to tune, defaults to 500. Samplers adjust the step sizes, scalings or
        similar during tuning. Tuning samples will be drawn in addition to the number specified in
        the ``draws`` argument, and will be discarded unless ``discard_tuned_samples`` is set to
        False.
    progressbar : bool
        Whether or not to display a progress bar in the command line. The bar shows the percentage
        of completion, the sampling speed in samples per second (SPS), and the estimated remaining
        time until completion ("expected time of arrival"; ETA).
    model : Model (optional if in ``with`` context)
    random_seed : int or list of ints
        A list is accepted if ``cores`` is greater than one.
    discard_tuned_samples : bool
        Whether to discard posterior samples of the tune interval.
    compute_convergence_checks : bool, default=True
        Whether to compute sampler statistics like Gelman-Rubin and ``effective_n``.

    Returns
    -------
    trace : pymc3.backends.base.MultiTrace
        A ``MultiTrace`` object that contains the samples.
    """
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章