7
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.

Google Colab環境でpystan 3.3を利用する

Posted at

はじめに

2022/9/1時点でPyStanのQuick Startに記載のコードをGoogle Colabo環境で動作させる際のメモです。

Pystan 3.5 Quick Start

import stan

schools_code = """
data {
  int<lower=0> J;         // number of schools
  real y[J];              // estimated treatment effects
  real<lower=0> sigma[J]; // standard error of effect estimates
}
parameters {
  real mu;                // population treatment effect
  real<lower=0> tau;      // standard deviation in treatment effects
  vector[J] eta;          // unscaled deviation from mu by school
}
transformed parameters {
  vector[J] theta = mu + tau * eta;        // school treatment effects
}
model {
  target += normal_lpdf(eta | 0, 1);       // prior log-density
  target += normal_lpdf(y | theta, sigma); // log-likelihood
}
"""

schools_data = {"J": 8,
                "y": [28,  8, -3,  7, -1,  1, 18, 12],
                "sigma": [15, 10, 16, 11,  9, 11, 10, 18]}

posterior = stan.build(schools_code, data=schools_data)
fit = posterior.sample(num_chains=4, num_samples=1000)
eta = fit["eta"]  # array with shape (8, 4000)
df = fit.to_frame()  # pandas `DataFrame, requires pandas

課題点

ビルド実行時にエラーが出ます。

posterior = stan.build(schools_code, data=schools_data, random_seed=1)
RuntimeError: asyncio.run() cannot be called from a running event loop

対処法

nest_asyncioをインストール

pip install nest_asyncio

PyStan インポート時に以下を追加しておく

import nest_asyncio
nest_asyncio.apply()
import stan

その他の注意

school_dataのデータの辞書のところは、手書きせずにpandasのデータフレームを使うと思いますが、Type Errorがでます。tolist()で変換すればいけました。

※以下は辞書指定時のイメージです。

schools_data = {"J": df.shape[0]
                "y": df["value"],
                "sigma": df["sigma"}

Type Errorでてしまいます。

TypeError: cannot convert the series to <class 'int'>

対処方法

schools_data = {"J": df.shape[0]
                "y": df["value"].tolist(),
                "sigma": df["sigma"].tolist()}

参考
WindowsマシンでPyStan3.2.0を使う
Google colaboratory上でのStanの使い方
Google ColabでPyStanがインポートできなくなってた件

7
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
7
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?