有關更多示例筆記本,請參見此處!
決策涉及了解不同變量如何相互影響並預測結果時,當其中一些變為新值時。例如,給定結果變量,人們可能有興趣確定潛在動作可能如何影響它,了解導致其當前價值的原因,或模擬如果某些變量更改,將會發生什麼。回答此類問題需要因果推理。 Dowhy是一個Python庫,可引導您完成因果推理的各個步驟,並提供了一個統一的界面來回答因果問題。
Dowhy為效果估計,預測,因果影響,因果結構的診斷,根本原因分析,干預措施和反事實提供了多種算法。 Dowhy的一個關鍵特徵是它的反駁和偽造API,可以測試任何估計方法的因果假設,從而使推斷更加穩健和可訪問非專家。
圖形因果模型和潛在結果:兩全其美
Dowhy建立在因果推斷的兩個最強大的框架上:圖形因果模型和潛在結果。為了進行效應估計,它使用基於圖的標準和DO-Calculus來建模假設並識別非參數因果效應。為了估計,它主要基於潛在結果切換到方法。
對於因果問題,它超出了效果估計,它通過通過每個節點的明確因果機制對數據生成過程進行建模來使用圖形因果模型的功能,例如,該機制可以解鎖能力將觀察到的效果歸因於特定變量或估算點上的對立面。
有關因果推論的快速介紹,請查看Amit-Sharma/Causal-inperial-Tutorial,我們還在ACM知識發現和數據挖掘(KDD 2018)會議上提供了更全面的教程:Causalinference.gitlab.io/kdd-tutorial 。有關因果推理的四個步驟及其對機器學習的影響的介紹,您可以從Microsoft Research Dowhy網絡研討會訪問該視頻教程,並介紹圖形因果模型API,請參閱Dowhy的PyCon介紹。
Dowhy支持以下因果任務:
有關更多詳細信息以及如何在實踐中使用這些方法,請查看https://py-why.github.io/dowhy的文檔
Dowhy支持Python 3.8+。要安裝,您可以使用Pip,Poetry或Conda。
最新版本
使用PIP安裝最新版本。
pip install dowhy
使用詩歌安裝最新版本。
poetry add dowhy
使用Conda安裝最新版本。
conda install -c conda-forge dowhy
如果您面對CONDA的“解決環境”問題,請嘗試使用conda update --all
全部安裝Dowhy。如果那不起作用,請使用conda config --set channel_priority false
然後嘗試再次安裝。如果問題仍然存在,請在此處添加您的問題。
開發版本
如果您希望使用最新的開發版本,則您的依賴關係管理工具將需要指向我們的GitHub存儲庫。
pip install git+https://github.com/py-why/dowhy@main
要求
Dowhy需要一些依賴項。有關特定版本的詳細信息,請參見pyproject.toml,toot.poetry.sportencies部分。
如果您遇到任何問題,請嘗試手動安裝依賴項。
pip install ' <dependency-name>==<version> '
(可選),如果您希望以點格式輸入圖形,請安裝pydot(或pygraphviz)。
對於看起來更好的圖形,您可以選擇安裝pygraphviz。要進行,請先安裝GraphViz,然後安裝Pygraphviz(在Ubuntu和Ubuntu WSL上)。
筆記
安裝pygraphviz可能會在某些平台上引起問題。對大多數Linux發行版有效的一種方法是首先安裝GraphViz,然後是Pygraphviz,如下所示。否則,請諮詢Pygraphviz的文檔。
sudo apt install graphviz libgraphviz-dev graphviz-dev pkg-config
pip install --global-option=build_ext
--global-option= " -I/usr/local/include/graphviz/ "
--global-option= " -L/usr/local/lib/graphviz " pygraphviz
大多數Dowhy中的大多數因果任務只需要寫幾行代碼。在這裡,我們闡明了治療對結果變量的因果影響:
from dowhy import CausalModel
import dowhy . datasets
# Load some sample data
data = dowhy . datasets . linear_dataset (
beta = 10 ,
num_common_causes = 5 ,
num_instruments = 2 ,
num_samples = 10000 ,
treatment_is_binary = True )
可以以不同的方式定義因果圖,但最常見的方式是通過NetworkX。加載數據後,我們使用四個主要操作進行DOWHY中的效果估計:模型,識別,估計和反駁:
# I. Create a causal model from the data and given graph.
model = CausalModel (
data = data [ "df" ],
treatment = data [ "treatment_name" ],
outcome = data [ "outcome_name" ],
graph = data [ "gml_graph" ]) # Or alternatively, as nx.DiGraph
# II. Identify causal effect and return target estimands
identified_estimand = model . identify_effect ()
# III. Estimate the target estimand using a statistical method.
estimate = model . estimate_effect ( identified_estimand ,
method_name = "backdoor.propensity_score_matching" )
# IV. Refute the obtained estimate using multiple robustness checks.
refute_results = model . refute_estimate ( identified_estimand , estimate ,
method_name = "random_common_cause" )
Dowhy對其產出的解釋性的應力。在分析中的任何時候,您都可以檢查未經測試的假設,確定的估計值(如果有)以及估算(如果有)。這是線性回歸估計器的樣本輸出:
有關完整的代碼示例,請查看Dowhy Notebook的入門。
您還可以使用ECONML的條件平均治療效果(CATE)估計方法,如條件治療效果筆記本所示。這是代碼段。
from sklearn . preprocessing import PolynomialFeatures
from sklearn . linear_model import LassoCV
from sklearn . ensemble import GradientBoostingRegressor
dml_estimate = model . estimate_effect ( identified_estimand , method_name = "backdoor.econml.dml.DML" ,
control_value = 0 ,
treatment_value = 1 ,
target_units = lambda df : df [ "X0" ] > 1 ,
confidence_intervals = False ,
method_params = {
"init_params" :{ 'model_y' : GradientBoostingRegressor (),
'model_t' : GradientBoostingRegressor (),
'model_final' : LassoCV (),
'featurizer' : PolynomialFeatures ( degree = 1 , include_bias = True )},
"fit_params" :{}})
Dowhy的圖形因果模型框架提供了強大的工具來解決因果問題,超出了效果估計。它基於Pearl的圖形因果模型框架,並通過因果機制顯式地對每個變量的因果數據生成過程進行建模,以支持廣泛的因果算法。有關更多詳細信息,請參見因果推論的書元素。
複雜的因果查詢,例如將觀察到的異常歸因於系統中的節點,只需幾行代碼即可執行:
import networkx as nx , numpy as np , pandas as pd
from dowhy import gcm
# Let's generate some "normal" data we assume we're given from our problem domain:
X = np . random . normal ( loc = 0 , scale = 1 , size = 1000 )
Y = 2 * X + np . random . normal ( loc = 0 , scale = 1 , size = 1000 )
Z = 3 * Y + np . random . normal ( loc = 0 , scale = 1 , size = 1000 )
data = pd . DataFrame ( dict ( X = X , Y = Y , Z = Z ))
# 1. Modeling cause-effect relationships as a structural causal model
# (causal graph + functional causal models):
causal_model = gcm . StructuralCausalModel ( nx . DiGraph ([( 'X' , 'Y' ), ( 'Y' , 'Z' )])) # X -> Y -> Z
gcm . auto . assign_causal_mechanisms ( causal_model , data )
# 2. Fitting the SCM to the data:
gcm . fit ( causal_model , data )
# Optional: Evaluate causal model
print ( gcm . evaluate_causal_model ( causal_model , data ))
# Step 3: Perform a causal analysis.
# results = gcm.<causal_query>(causal_model, ...)
# For instance, root cause analysis:
anomalous_sample = pd . DataFrame ( dict ( X = [ 0.1 ], Y = [ 6.2 ], Z = [ 19 ])) # Here, Y is the root cause.
# "Which node is the root cause of the anomaly in Z?":
anomaly_attribution = gcm . attribute_anomalies ( causal_model , "Z" , anomalous_sample )
# Or sampling from an interventional distribution. Here, under the intervention do(Y := 2).
samples = gcm . interventional_samples ( causal_model , interventions = { 'Y' : lambda y : 2 }, num_samples_to_draw = 100 )
除這些示例外,GCM框架提供了更多功能。有關完整的代碼示例,請查看在線商店示例筆記本。
有關更多功能,請參見Dowhy的示例應用程序以及有關輸出的詳細信息,請參見用戶指南或結帳Jupyter筆記本。
微軟研究博客|視頻效果估計教程|根本原因分析的視頻教程| Arxiv紙| Arxiv紙(圖形因果模型擴展)|幻燈片
如果您發現Dowhy對您的工作有用,請引用以下兩個參考文獻:
Bibtex:
@article {dowhy, title = {dowhy:因果推理的端到端庫}, 作者= {Sharma,Amit和Kiciman,Emre}, journal = {arxiv預印arxiv:2011.04216}, 年= {2020} } @Article {JMLR:V25:22-1258, 作者= {patrick bl {{“ o}} baum和Peter G {{” O}} tz和Kailash Budhathoki和Atalanti A. Mastakouri和Dominik Janzing}, title = {dowhy-gcm:在圖形因果模型中用於因果推斷的dowhy的擴展 日記= {機器學習研究期刊}, 年= {2024}, 音量= {25}, 數字= {147}, 頁= {1--7}, url = {http://jmlr.org/papers/v25/22-1258.html} }
如果您遇到問題或對Dowhy有特定的要求,請提出問題。
該項目歡迎貢獻和建議。有關貢獻和所有貢獻者列表的指南,請查看貢獻。md和我們的文檔以獲取貢獻代碼。我們的撰稿人行為準則可在此處獲得。