LoginSignup
7
12

More than 3 years have passed since last update.

Pystanのインストール(anaconda環境)

Last updated at Posted at 2019-11-09

インストール環境

Win10 pro 64 bit
Anaconda環境 (conda4.7)

リポジトリconda-forgeの追加

anacondaでは、conda とpipのインストールが混在すると環境が壊れることがあります。
condaとpip:混ぜるな危険
Jupyter Notebookが起動しないと思ったらAnaconda環境が壊れていた
ですので、できるだけcondaだけでインストールしたほうが良いです。
conda-forgeは、github上のコミュニティ主体のパッケージコレクションで、たくさんのパッケージを公開しており、condaのdefaultsでは見つからないパッケージをダウンロードすることが可能です。
condaのパッケージ参照リポジトリにconda-forgeをリポジトリ先に加えることがおすすめです。
condaが探すリポジトリ先を変更する方法(conda-forgeの追加)
以下参照記事のコピー


condaが探すリポジトリ先を確認します

conda config --get channels
--add channels 'defaults'   # lowest priority

defaultsを探しにいっていることがわかります。
そこで、探す先にconda-forgeを追加します。

$conda config --append channels conda-forge

conda-forgeが追加されたことを確認します。

$conda config --get channels
--add channels 'conda-forge'   # lowest priority
--add channels 'defaults'   # highest priority

conda仮想環境へのpystanのインストール

conda-forgeのリポジトリにはPystanのパッケージが存在します。
https://anaconda.org/conda-forge/pystan
PyStan on Windows
に詳しく書いたあります。それに従ってインストールします。

anaconda promptを開いて

conda create -n stan python=3.6

と入力します。

-n の後は自由に名前を付けることができます。今回はstanとしています。
pythonは3.6としています。3.6以上を入れる必要があります。
これでpython=3.6が入った仮想環境ができます。

conda activate stan

と入力しstanの仮想環境に入ります。

そうすると
(base)C:\User\username> だったものが
(stan)C:\User\username> に変わります。

ここでパッケージのインストールを行います。

conda install Cython Numpy pystan

さらに

conda install matplotlib jupyter

などをインストールします。必要があれば、scipy pandas などもconda でインストールします。
C++ compilerをインストールします。

conda install libpython m2w64-toolchain -c msys2

PYTHONPATH\\Lib\\distutils にある distutils.cfgに次のコマンドを付け加えます。

[build]
compiler=mingw32

jupyter notebookでの仮想環境の切り替え

Condaで作ってる仮想環境の切り替えをJupyter上で簡単に行う方法
Anacondaの仮想環境をJupyter notebookに反映させる方法

jupyter notebookからcondaで作成した仮想環境を簡単に使えるように設定します。
まず仮想環境のstanから抜けます

conda deactivate 
(base)C:\User\username> になります。

そこで、以下のコマンドを入力します。(以下、上記参照のコピー)

pip install environment_kernels
jupyter notebook --generate-config

~/.jupyter/jupyter_notebook_config.py
という設定ファイルが生成されていると思います。
このファイルをテキストエディターなどで開いて、以下の設定を書き込みます。

c.NotebookApp.kernel_spec_manager_class='environment_kernels.EnvironmentKernelSpecManager'
c.EnvironmentKernelSpecManager.env_dirs=['仮想環境が生成されているパス']

私の場合: '仮想環境が生成されているパス'= 'C:\Users\Username\Anaconda3\envs'
これでJupyterでPystanが使える環境ができるはずです。

動作確認

環境構築後
jupyter notebookを開いて、仮想環境としてstanを選んで、以下のようなテストコードを入力してみてください。
おっさんが挑むPyStanによるMCMC~インストール編~

import pystan
# import numpy as np
# import matplotlib.pyplot as plt
%matplotlib inline

schools_dat = {'J': 8, 'y': [28,  8, -3,  7, -1,  1, 18, 12],'sigma': [15, 10, 16, 11,  9, 11, 10, 18]}
schools_code = """
data {
    int<lower=0> J; // number of schools
    real y[J]; // estimated treatment effects
    real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
    real mu;
    real<lower=0> tau;
    real eta[J];
}
transformed parameters {
    real theta[J];
    for (j in 1:J)
    theta[j] = mu + tau * eta[j];
}
model {
    eta ~ normal(0, 1);
    y ~ normal(theta, sigma);
}
"""
sm = pystan.StanModel(model_code=schools_code)
fit = sm.sampling(data=schools_dat, iter=1000, chains=4)
------------
INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_cbe9cd2f1e5ab5d1c7cce1f23ca970b4 NOW.
WARNING:pystan:1 of 2000 iterations ended with a divergence (0.05 %).
WARNING:pystan:Try running with adapt_delta larger than 0.8 to remove the divergences.
------------

上記の命令でコンパイルが始まります。エラーなどが出る場合はこちらを参照してください。
PyStan on Windows

la = fit.extract(permuted=True)
print(la['mu'])
------------
[ 2.58420099  7.99739289  4.00372858 ... 13.27834916  6.86538085
  3.91047685]
------------
la['mu'].shape
------------
(2000,)
------------
print(fit)
------------
Inference for Stan model: anon_model_cbe9cd2f1e5ab5d1c7cce1f23ca970b4.
4 chains, each with iter=1000; warmup=500; thin=1; 
post-warmup draws per chain=500, total post-warmup draws=2000.

           mean se_mean     sd   2.5%    25%    50%    75%  97.5%  n_eff   Rhat
mu         8.01    0.15    5.0  -1.69   4.62   7.97  11.18  18.19   1083    1.0
tau         6.5    0.22   5.76   0.35    2.3   5.03   9.02  20.53    686   1.01
eta[1]     0.37    0.02   0.95  -1.54  -0.27    0.4   1.03   2.18   1701    1.0
eta[2]   6.2e-4    0.02    0.9   -1.8  -0.58-6.4e-3   0.59   1.75   2426    1.0
eta[3]    -0.22    0.02   0.93   -2.0  -0.84  -0.23   0.39   1.72   1929    1.0
eta[4]    -0.03    0.02   0.88  -1.74  -0.65  -0.04   0.56   1.72   1788    1.0
eta[5]    -0.35    0.02   0.88  -2.07  -0.93  -0.36   0.22   1.44   1732    1.0
eta[6]     -0.2    0.02   0.92  -2.06  -0.78   -0.2   0.39   1.59   2007    1.0
eta[7]     0.32    0.02   0.86  -1.39  -0.23   0.31   0.89   1.94   2004    1.0
eta[8]     0.03    0.02   0.92  -1.69  -0.59   0.02   0.61   1.87   1682    1.0
theta[1]  11.33    0.25   8.45  -1.69   5.73  10.07  15.61  32.57   1173    1.0
theta[2]   8.14    0.12   6.24  -4.42   4.13   8.01  11.73  21.98   2780    1.0
theta[3]   5.79    0.19   7.85 -12.05   1.72   6.53  10.58  19.89   1658    1.0
theta[4]   7.59    0.15   6.55  -5.96   3.43   7.67  11.63  21.41   2018    1.0
theta[5]   4.97    0.15   6.61  -9.97   1.24   5.52   9.27   17.2   1849    1.0
theta[6]   6.15    0.17    6.7  -9.04    2.3   6.63  10.46  18.87   1565    1.0
theta[7]  10.68    0.18   6.77   -0.5   6.23  10.03  14.28   26.5   1402    1.0
theta[8]   8.37    0.23   8.06  -7.13   3.85   8.01  12.33  25.96   1221    1.0
lp__      -4.89     0.1   2.61 -10.75  -6.45  -4.71  -3.11   -0.3    690   1.01

Samples were drawn using NUTS at Fri Nov  8 09:59:19 2019.
For each parameter, n_eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor on split chains (at 
convergence, Rhat=1).
------------
fit.plot()
7
12
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
12