Stan Math Libraryでディリクレ分布からサンプルする
必要なソフト
- Stan Math Library(stan-dev/math · GitHub)
- Eigen(Eigen)
- Boost(Boost C++ Libraries)
ちなみにStan Math Libraryはnew BSD licenseです。
コンパイラはVisual Studio 2012を使用したのですが、erf()などが未定義とのエラーになりました。erf()はVisual Studio 2015では標準で対応しているので、今回はVisual Studio 2015を使用しています。
とはいえ、それでもエラーがいくつかでました。double smallの変数名を変えるのと、プリプロセッサに_SCL_SECURE_NO_WARNINGSを追加することで動きます。他にも内部コンパイルエラーとなったり少々あやしいです。
実装
ちょっと前の記事でディリクレ分布からのサンプリングをしました。wildpie.hatenablog.com
これと同じ内容を再現してみます。
プログラムで重要な部分は
stan::math::dirichlet_rng(alpha, engine)です。αを指定するとサンプリング値が返ってきます。結果も前回の記事と同じになりました。
ドキュメントが見当たらないので、何ができるか把握できていませんが使い勝手は良さそうです。
#include <iostream> #include <fstream> #include <random> #include <Eigen/Core> using namespace Eigen; #include <stan/math.hpp> int main() { VectorXd alpha(3); alpha << 8.0, 2.0, 2.0; std::default_random_engine engine; std::ofstream ofs("result.csv"); for (int i = 0; i < 10000; i++) { VectorXd x = stan::math::dirichlet_rng(alpha, engine); ofs << x(0) << "," << x(1) << "," << x(2) << std::endl; } ofs.close(); }