LiNGAMを用いた因果探索
② LiNGAMを用いた因果探索
ここでは、非ガウス性分布を仮定して因果関係を推定するLiNGAMを使用したコード例です。
# 必要なライブラリをインストール
!pip
install lingam matplotlib pandas numpy
# ライブラリのインポート
import
numpy as np
import
pandas as pd
import
matplotlib.pyplot as plt
from
lingam import DirectLiNGAM
# データ生成:気温、アイスクリーム売上、水泳事故件数
np.random.seed(42)
n_samples
= 300
temperature
= np.random.uniform(20, 40, n_samples) # 気温
ice_cream_sales
= temperature + np.random.normal(0, 2, n_samples) # アイスクリーム売上
swimming_accidents
= temperature + np.random.normal(0, 1, n_samples) # 水泳事故件数
# データフレームにまとめる
data
= pd.DataFrame({
'Temperature': temperature,
'IceCreamSales': ice_cream_sales,
'SwimmingAccidents': swimming_accidents
})
#
LiNGAMモデルを用いた因果推定
model
= DirectLiNGAM()
model.fit(data)
adjacency_matrix
= model.adjacency_matrix_ # 因果行列の取得
# 因果関係の表示
print("Adjacency
Matrix:")
print(adjacency_matrix)
# 因果グラフの描画
import
networkx as nx
labels
= data.columns.tolist()
graph
= nx.DiGraph()
for
i, source in enumerate(labels):
for j, target in enumerate(labels):
if adjacency_matrix[i, j] != 0:
graph.add_edge(source, target,
weight=adjacency_matrix[i, j])
# グラフの可視化
pos
= nx.spring_layout(graph)
nx.draw(graph,
pos, with_labels=True, node_size=3000, font_size=10)
nx.draw_networkx_edge_labels(graph,
pos, edge_labels={(u, v): f"{d['weight']:.2f}" for u, v, d in
graph.edges(data=True)})
plt.title("Causal
Graph Estimated by LiNGAM")
plt.show()
出力結果
Requirement
already satisfied: lingam in /usr/local/lib/python3.11/dist-packages (1.9.1)
~省略~
Requirement
already satisfied: typing_extensions>3.10.0.2 in
/usr/local/lib/python3.11/dist-packages (from
python-utils>=3.8.1->progressbar2->psy->lingam) (4.14.0)
Adjacency
Matrix:
[[0. 0. 0. ]
[1.02622471 0. 0. ]
[0.98429543 0. 0. ]]