0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

データをフィッティングする分布の選択

Last updated at Posted at 2022-10-09

問題設定

与えられたデータがあり, そのデータが従う確率分布としてどのようなものが適切か知りたい状況を想定する.

今回用いる方法

手当たり次第分布を持ってきて, パラメータのフィッティングを行う. フィッティングして得られた最適な分布とデータの経験分布を比べ, コルモゴロフ-スミルノフ検定(KS test)を行う.

使用環境

Python 3.10
Numpy 1.22
Scipy 1.9

コード例

import numpy as np
import pandas as pd
from scipy import stats

def compare_distribution(data: np.ndarray):
    result = []
    all_dists = [d for d in dir(stats) if isinstance(getattr(stats, d), stats.rv_continuous)]
    for dist in all_dists:
        dist_object = getattr(stats, dist)
        try:
            param = dist_object.fit(data)
            param_, loc, scale = param[:-2], param[-2], param[-1]
            if not param:
                D, p = stats.kstest(data, dist_object.cdf, args=(param_, loc, scale))
            else:
                D, p = stats.kstest(data, dist_object.cdf, args=(loc, scale))
        except:
            param, D, p = np.nan, np.nan, np.nan
            pass
        
        result.append({'distribution': dist,
                       'D': D,
                       'p': p,
                       'param': param
                      })
    return pd.DataFrame.from_records(result)

df = compare_distribution(data)

display(df)

あとがき

持ってきた分布の中に, 適切な分布が存在しない場合も当然ありうることに注意する. データ解析をやるときに頻繁にデータが従う分布候補の特定を行うので, 関数化しておくと便利そうだ.

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?