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?

pythonでcausalimactを使おうとしたら詰まった

Posted at

pythonでcausalimpactを使おうとしたら詰まったので、同様の人に向けて共有。

結論:google colabなら実行できる。ローカル環境なら微妙。

背景

金本拓著の書籍「因果推論」の7章にてcausalimpactのハンズオンをやっていた。
環境はローカルにまっさらな仮想環境を構築。

  • python==3.10.12

詰まったところ

pip install tfcusalimpact==0.0.13

ライブラリをインストールし、インポート中にエラー

from causalimpact import CausalImpact

#出力
This version of TensorFlow Probability requires TensorFlow version >= 2.18;
Detected an installation of version 2.16.2. Please upgrade TensorFlow to proceed.

TensorFlowのバージョンが2.18以上が必要らしい。
ここで、TensorFlowの安定版は2.16.2(2025年3月16日時点)であり、pipではインストールできないらしい。
理由としてはPyPI(Python Package Index) と呼ばれる公開リポジトリに2.16.2までしか置いてないらしい。(2.18はまだ開発段階っぽい?)

開発段階でもいいので強引にインストールしたく、下記を実行。

pip install tf-nightly

# 出力
ERROR: Could not find a version that satisfies the requirement tf-nightly (from versions: none)
ERROR: No matching distribution found for tf-nightly

そんなものはないらしいです。。。。

tf-nightlyについては下記を参考にすればいいかもしれませんが、深みにハマりそうなので一旦STOPしました。
https://www.tensorflow.org/probability/install?hl=ja

別のcusalimpactパッケージ

pythonのcusalimpactパッケージにはpycausalimpactというものがあるらしいので、そちらを試してみた。
前評判は下記の記事を参考に。
(すでにgithub repoからは消えており、またtfcausalimpactやRのcausalimpactパッケージとそれぞれ結果が違うらしい。)

https://tomtom58.hatenablog.com/entry/2025/02/10/210737
https://tjo.hatenablog.com/entry/2023/12/04/170000
途中経過を省きますが、ハンズオンの手本の結果と同じことを確認しました。

#推定結果の要点を出力
print(ci.summary())

#出力
osterior Inference {Causal Impact}
                          Average            Cumulative
Actual                    64.97              1884.2
Prediction (s.d.)         50.82 (0.5)        1473.82 (14.58)
95% CI                    [49.8, 51.77]      [1444.07, 1501.21]

Absolute effect (s.d.)    14.15 (0.5)        410.38 (14.58)
95% CI                    [13.21, 15.18]     [382.99, 440.13]

Relative effect (s.d.)    27.84% (0.99%)     27.84% (0.99%)
95% CI                    [25.99%, 29.86%]   [25.99%, 29.86%]

Posterior tail-area probability p: 0.0
Posterior prob. of a causal effect: 100.0%

For more details run the command: print(impact.summary('report'))

がしかし、プロットは縦軸が調整できない。

ci.plot()

image.png
縦軸を調整しようとしたが、github ripoにもplot()のコードの中身がないので、断念しました。
*わかる人教えてください。。。

本当はこんなプロットになるはず(google colab版)
スクリーンショット 2025-03-16 16.18.46.png

展望

causalimpactを使用するときは、google colabもしくはRでやろうと思います。google colabだと安定版じゃないTensolFlowを使用しているから、使用できるんですかね。後々再現できないとかならないだろうか。
TensolFlow==2.18の安定版がpip installできたら、またチャレンジしようと思います。

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?