メインコンテンツへスキップ
見出し画像

「ベイズ統計モデリングによるデータ分析入門」をPythonで写経 ~ 補助記事:stantoolsモジュール

    書籍の著者 馬場真哉 先生


    この記事は、書籍「RとStanではじめるベイズ統計モデリングによるデータ分析入門」第5部「【応用編】状態空間モデル」で使うモジュール「stantools」の準備作業を紹介する補助記事です。

    ⚙️⚙️⚙️

    ⚙️ モジュールの内容
    モジュール「stantools」には以下の2関数を含みます。
    ・Stan ファイルの書き込み関数
    ・状態空間モデルを図示する関数

    📑 ファイルの作成
    このモジュールを以下のファイル名で作成します。
    ファイル名:stantools.py

    # ヘルパー関数集 stantools
    
    # インポート
    import os
    import arviz as az                       # type: ignore
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import numpy as np
    plt.rcParams['font.family'] = 'Meiryo'
    
    
    # stanファイルの書き込み関数
    def write_stan_file(stan_code, stan_path): 
        '''stanファイルを書き込む
    
        Parameters
        ----------
        stan_code : str
            stanコード
        stan_path : str
            stanファイルのフルパス
        
        Returns
        -------
        None
    
        ''' 
    
        # 同一コードのStanファイルが存在する場合、ファイルを更新しないで終了
        if os.path.exists(stan_path):
            with open(stan_path, 'r', encoding='utf-8') as f:
                current_stan_code = f.read()
            if current_stan_code == stan_code:
                print('既存のStanファイルと同一コードのため、更新しないで終了しました')
                return
        
        # 同一コードのStanファイルが存在しない場合、ファイルを作成・更新する
        with open(stan_path, 'w', encoding='utf-8') as f:
            f.write(stan_code)
        print('Stanファイルを更新しました')
    
    
    # 状態空間モデルを図示する関数
    
    def plot_state_space_models(
            idata, times, obs, state_name, graph_title, ylabel,
            freq='month', freq_interval=1, figsize=(10, 4),
            group='posterior', alpha=0.05):
        
        '''MCMCサンプル等から時系列プロットを作成する
    
        Parameters
        ----------
        idata : arviz inference data
            MCMCサンプルデータ
        times : pandas DatetimeIndex
            時間軸
        obs : pandas Series
            観測値
        state_name : str
            MCMCサンプルデータ内の状態変数名
        graph_title : str
            グラフタイトル
        ylabel : str
            y軸ラベル
        freq : str
            x軸目盛りラベルの表示単位
            年単位: 'year', 月単位: 'month'(デフォルト), 日単位: 'date'
        freq_interval : int
            x軸目盛りラベルの間隔。デフォルト:1
        figsize: tuple
            グラフサイズ。デフォルト:figsize=(10, 4)
        group : str
            idata のグループ名。デフォルト: 'posterior'
        alpha : float
            1 - 信用区間の割合。デフォルト: 0.05
      
        Returns
        -------
        None
    
        ''' 
    
        ## データの準備
        # idataから状態変数を取り出し
        states = az.extract(idata[group])[state_name].data
        # 状態変数の100(α/2)%, 50%, 100(1-α/2)%点を算出
        states_quantile = np.quantile(states, q=[alpha/2, 0.5, 1-alpha/2], axis=1)
        
        ## 描画処理
        # 描画領域の設定
        fig, ax = plt.subplots(figsize=figsize)
        # obsが設定されている場合、観測値の散布図を描画
        if obs is not None:
            ax.scatter(x=times, y=obs, s=10)
        # 状態の中央値の折れ線グラフの描画
        ax.plot(times, states_quantile[1, :], color='tab:red')
        # 状態の95%信用区間の塗りつぶし描画
        ax.fill_between(times, *states_quantile[[0, 2], :], color='tomato',
                         alpha=0.2)
        # 修飾:タイトル、x軸ラベル、y軸ラベル
        ax.set_title(graph_title, loc='left')
        ax.set_xlabel('time', fontsize=12)
        ax.set_ylabel(ylabel, fontsize=12)
    
        # x軸目盛りラベルの日付の表示
        # 年単位で表示する場合
        if freq == 'year':
            ax.xaxis.set_major_locator(mdates.YearLocator(base=freq_interval))
            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y年'))
        # 月単位で表示する場合
        elif freq == 'month':
            ax.xaxis.set_major_locator(mdates.MonthLocator(interval=freq_interval))
            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y年%m月'))
        # 日単位で表示する場合
        elif freq == 'date':
            ax.xaxis.set_major_locator(mdates.DayLocator(interval=freq_interval))
            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y年%m月%d日'))
        
        plt.show()

    📁 ファイルを保存するフォルダ
    Jupyter Notebook(各記事のコード)と同じフォルダに保存します。

    💻️ インポート方法

    # ユーティリティ
    import stantools                 

    ⚙️⚙️⚙️

    最後までお読みいただきまして、ありがとうございました。

     
     
    「のんびり統計」です。 データサイエンス/統計の情報を発信をします! 多くの方と一緒に楽しくデータサイエンスを学べる場を目指しています。

    あなたへのおすすめ