dowhy.utils 包#

子模块#

dowhy.utils.api 模块#

dowhy.utils.api.parse_state(state)[source]#

dowhy.utils.cit 模块#

dowhy.utils.cit.compute_ci(r=None, nx=None, ny=None, confidence=0.95)[source]#

计算相关系数的参数置信区间。参见:https://online.stat.psu.edu/stat505/lesson/6/6.3

这通过应用 Fisher r 到 z 变换来实现:z = .5[ln((1+r)/(1-r))] = arctanh(r)

标准误差为 1/sqrt(N-3),其中 N 为样本大小

对应置信水平下正态分布的临界值通过 stats.norm.ppf((1 - alpha)/2) 计算,用于双尾检验

z 空间中的下限和上限置信区间通过公式 z ± 临界值*误差 计算

然后将置信区间转换回 r 空间

:param stat : 相关系数 :param nx : 向量 x 的长度 :param ny : 向量 y 的长度 :param confidence : 置信水平 (0.95 = 95%)

:returns : 包含置信区间的数组

dowhy.utils.cit.conditional_MI(data=None, x=None, y=None, z=None)[source]#

在给定 Z 的情况下返回 X 和 Y 之间的条件互信息的方法:I(X, Y | Z) = H(X|Z) - H(X|Y,Z)

= H(X,Z) - H(Z) - H(X,Y,Z) + H(Y,Z) = H(X,Z) + H(Y,Z) - H(X,Y,Z) - H(Z)

:param data : 数据集 :param x,y,z : 数据集中的列名 :returns : 在给定 Z 的情况下 X 和 Y 之间的条件互信息

dowhy.utils.cit.entropy(x)[source]#

” 返回随机变量 x 的熵 H(x) = - Σ p(x)log(p(x)) :param x : 要计算熵的随机变量 :returns : 随机变量的熵

dowhy.utils.cit.partial_corr(data=None, x=None, y=None, z=None, method='pearson')[source]#

计算偏相关,即在移除 z 的影响后 x 和 y 之间的关联程度。这通过计算两个线性回归(xsim z, ysim z)残差之间的相关系数来实现。参见:1 https://en.wikipedia.org/wiki/Partial_correlation

:param data : pandas dataframe :param x : 数据中的列名 :param y : 数据中的列名 :param z : 字符串或列表 :param method : 指示相关类型(“pearson” 或 “spearman”)的字符串

: returns: 一个 Python 字典,其键为

n: 样本大小 r: 偏相关系数 CI95: 95% 参数置信区间 p-val: p 值

dowhy.utils.cli_helpers 模块#

dowhy.utils.cli_helpers.query_yes_no(question, default=True)[source]#

通过标准输入提问是/否问题并返回答案。

来源:https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input

如果输入无效,将一直询问用户直到其给出有效输入。

副作用:阻塞程序执行,直到给出有效输入 (y/n)。

参数:
  • question(str) – 呈现给用户的问题。

  • default(bool|None) – 在未输入值按下 Enter 时使用的默认值。当为 None 时,没有默认值,并且查询将循环。

返回:

一个布尔值,指示用户是输入了“是”还是“否”。

dowhy.utils.dgp 模块#

class dowhy.utils.dgp.DataGeneratingProcess(**kwargs)[source]#

基类: object

数据生成过程实现的基础类。

子类实现了创建各种数据生成过程的函数。所有数据生成过程都位于“dowhy.utils.dgps”包中。

DEFAULT_PERCENTILE = 0.9#
convert_to_binary(data, deterministic=False)[source]#
generate_data()[source]#
generation_process()[source]#

dowhy.utils.graph_operations 模块#

dowhy.utils.graph_operations.add_edge(i, j, g)[source]#

向图 g 添加一条边 i –> j。只有当添加该边不会导致图中出现循环时,才会添加该边。

dowhy.utils.graph_operations.adjacency_matrix_to_adjacency_list(adjacency_matrix, labels=None)[source]#

将图的邻接矩阵转换为邻接表。

参数:
  • adjacency_matrix – 表示图邻接矩阵的 numpy 数组。

  • labels – 标签列表。

返回:

以字典形式表示的邻接表。

dowhy.utils.graph_operations.adjacency_matrix_to_graph(adjacency_matrix, labels=None)[source]#

将给定的图邻接矩阵转换为 DOT 格式。

参数:
  • adjacency_matrix – 表示图邻接矩阵的 numpy 数组。

  • labels – 标签列表。

返回:

DOT 格式的图。

dowhy.utils.graph_operations.convert_to_undirected_graph(g)[source]#
dowhy.utils.graph_operations.daggity_to_dot(daggity_string)[source]#

将输入的 daggity_string 转换为有效的 DOT 图格式。

参数:

daggity_string – 从 Daggity 网站导出的图

返回:

DOT 字符串

dowhy.utils.graph_operations.del_edge(i, j, g)[source]#

删除图 g 中的边 i –> j。只有当删除该边不会导致图不连通时,才会删除该边。

dowhy.utils.graph_operations.find_ancestor(node_set, node_names, adjacency_matrix, node2idx, idx2node)[source]#

在给定图中查找给定节点集的祖先。

参数:
  • node_set – 必须获取其祖先的节点集。

  • node_names – 图中所有节点的名称。

  • adjacency_matrix – 图邻接矩阵。

  • node2idx – 将节点名称映射到其在邻接矩阵中的行或列索引的字典。

  • idx2node – 将邻接矩阵中的行或列索引映射到相应节点名称的字典。

返回:

包含 node_set 中所有节点的祖先的 OrderedSet。

dowhy.utils.graph_operations.find_c_components(adjacency_matrix, node_set, idx2node)[source]#

在图中获取 C-components。

参数:
  • adjacency_matrix – 图邻接矩阵。

  • node_set – 必须获取其祖先的节点集。

  • idx2node – 将邻接矩阵中的行或列索引映射到相应节点名称的字典。

返回:

图中 C-components 的列表。

dowhy.utils.graph_operations.find_predecessor(i, j, g)[source]#

在图 g 中,查找节点 i 和 j 之间路径上的前驱节点 k。

dowhy.utils.graph_operations.get_random_node_pair(n)[source]#

随机生成一对节点。

dowhy.utils.graph_operations.get_simple_ordered_tree(n)[source]#

生成一个简单有序树。该树是一个包含 n 个节点的有向无环图,其结构为 0 –> 1 –> …. –> n。

dowhy.utils.graph_operations.induced_graph(node_set, adjacency_matrix, node2idx)[source]#

获取与节点子集对应的导出子图。

参数:
  • node_set – 必须获取其祖先的节点集。

  • adjacency_matrix – 图邻接矩阵。

  • node2idx – 将节点名称映射到其在邻接矩阵中的行或列索引的字典。

返回:

表示导出子图邻接矩阵的 Numpy 数组。

dowhy.utils.graph_operations.is_connected(g)[source]#

检查有向无环图是否连通。

dowhy.utils.graph_operations.str_to_dot(string)[source]#

将 graphviz 库的输入字符串转换为有效的 DOT 图格式。

参数:

string – DOT 格式的图。

返回:

转换为适合 DoWhy 库使用的 DOT 字符串。

dowhy.utils.graphviz_plotting 模块#

dowhy.utils.graphviz_plotting.plot_causal_graph_graphviz(causal_graph: Graph, layout_prog: str | None = None, display_causal_strengths: bool = True, causal_strengths: Dict[Tuple[Any, Any], float] | None = None, colors: Dict[Any | Tuple[Any, Any], str] | None = None, filename: str | None = None, display_plot: bool = True, figure_size: Tuple[int, int] | None = None) None#

dowhy.utils.networkx_plotting 模块#

dowhy.utils.networkx_plotting.plot_causal_graph_networkx(causal_graph: Graph, layout_prog: str | None = None, causal_strengths: Dict[Tuple[Any, Any], float] | None = None, colors: Dict[Any | Tuple[Any, Any], str] | None = None, filename: str | None = None, display_plot: bool = True, label_wrap_length: int =3, figure_size: Tuple[int, int] | None = None) None#

dowhy.utils.ordered_set 模块#

class dowhy.utils.ordered_set.OrderedSet(elements=None)[source]#

基类: object

Python 有序集合类。代码取自 buyalsky/ordered-hash-set

add(element)[source]#

如果元素不存在,则将其添加到集合中的函数。

参数:

element – 要添加的元素。

difference(other_set)[source]#

从 self._set 中移除同时存在于 other_set 中的元素的函数。

参数:

other_set – 用于求差集的集合。可以是列表、集合或 OrderedSet。

返回:

表示 self._set 和 other_set 中元素差集的新 OrderedSet。

get_all()[source]#

返回集合中所有元素列表的函数。

返回:

集合中所有项的列表。

intersection(other_set)[source]#

计算 self._set 和 other_set 交集的函数。

参数:

other_set – 用于求交集的集合。可以是列表、集合或 OrderedSet。

返回:

表示 OrderedSet 对象和 other_set 中共有元素集合的新 OrderedSet。

is_empty()[source]#

判断集合是否为空的函数。

返回:

如果集合为空,则为 True,否则为 False

union(other_set)[source]#

计算 self._set 和 other_set 并集的函数。

参数:

other_set – 用于求并集的集合。可以是列表、集合或 OrderedSet。

返回:

表示 OrderedSet 对象和 other_set 中所有元素集合的新 OrderedSet。

dowhy.utils.plotting 模块#

dowhy.utils.plotting.bar_plot(values: Dict[str, float], uncertainties: Dict[str, Tuple[float, float]] | None = None, ylabel: str = '', filename: str | None = None, display_plot: bool = True, figure_size: List[int] | None = None, bar_width: float =0.8, xticks: List[str] | None =None, xticks_rotation: int =90, sort_names: bool =False) None#

方便的函数,用于制作给定值(如果提供不确定性条)的条形图。对于各种归因结果(包括置信区间)非常有用。

参数:
  • values – 一个字典,其中键是标签,值是要绘制的值。

  • uncertainties – 要添加到误差条的属性字典。

  • ylabel – y 轴的标签。

  • filename – 如果输出应绘制到文件中,则为可选文件名。

  • display_plot – 可选指定是否应显示图(默认为 True)。

  • figure_size – 要绘制的图的大小。

  • bar_width – 条的宽度。

  • xticks – 明确指定 x 轴上条的标签。

  • xticks_rotation – 指定 x 轴上标签的旋转角度。

  • sort_names – 如果为 True,则图中的名称按字母顺序排序。如果为 False,则使用 values 中给定的顺序。

dowhy.utils.plotting.plot(causal_graph: Graph, layout_prog: str | None = None, causal_strengths: Dict[Tuple[Any, Any], float] | None = None, colors: Dict[Any | Tuple[Any, Any], str] | None = None, filename: str | None = None, display_plot: bool = True, figure_size: Tuple[int, int] | None = None, **kwargs) None#

方便的函数,用于绘制因果图。此函数根据系统中可用的后端使用不同的实现。使用 Graphviz 作为后端时可获得最佳结果。这需要共享系统库(例如 brew install graphvizapt-get install graphviz)以及 Python pygraphviz 包(pip install pygraphviz)。如果 graphviz 不可用,它将回退到 networkx 后端。

参数:
  • causal_graph – 要绘制的图

  • layout_prog – 定义布局类型。如果给定 None,则 graphviz 图使用 'dot' 布局,networkx 图使用自定义布局。

  • causal_strengths – 一个可选字典,包含 Edge -> float 条目。

  • colors – 一个可选字典,包含边或节点的颜色规范。

  • filename – 如果输出应绘制到文件中,则为可选文件名。

  • display_plot – 可选指定是否应显示图(默认为 True)。

  • figure_size – 一个元组,用于定义 pyplot 的宽度和高度(作为元组)。这用于修改 pyplot 的 'figure.figsize' 参数。如果给定 None,则使用当前/默认值。

  • kwargs – 其余参数将原样传递给后端。

使用示例:

>>> plot(nx.DiGraph([('X', 'Y')])) # plots X -> Y
>>> plot(nx.DiGraph([('X', 'Y')]), causal_strengths={('X', 'Y'): 0.43}) # annotates arrow with 0.43
>>> plot(nx.DiGraph([('X', 'Y')]), colors={('X', 'Y'): 'red', 'X': 'green'}) # colors X -> Y red and X green
dowhy.utils.plotting.plot_adjacency_matrix(adjacency_matrix: DataFrame, is_directed: bool, filename: str | None = None, display_plot: bool =True) None#
dowhy.utils.plotting.pretty_print_graph(graph: DiGraph) None#

美化打印包含时间滞后的图边。

参数:

graph (networkx.Graph) – networkx 图。

返回:

None

返回类型:

None

dowhy.utils.propensity_score 模块#

dowhy.utils.propensity_score.binarize_discrete(data, covariates, variable_types)[source]#
dowhy.utils.propensity_score.binary_treatment_model(data, covariates, treatment, variable_types)[source]#
dowhy.utils.propensity_score.categorical_treatment_model(data, covariates, treatment, variable_types)[source]#
dowhy.utils.propensity_score.continuous_treatment_model(data, covariates, treatment, variable_types)[source]#
dowhy.utils.propensity_score.discrete_to_integer(discrete)[source]#
dowhy.utils.propensity_score.get_type_string(variables, variable_types)[source]#
dowhy.utils.propensity_score.propensity_of_treatment_score(data, covariates, treatment, model='logistic', variable_types=None)[source]#
dowhy.utils.propensity_score.state_propensity_score(data, covariates, treatments, variable_types=None)[source]#

dowhy.utils.regression 模块#

dowhy.utils.regression.create_polynomial_function(max_degree)[source]#

创建多项式函数列表

参数:

max_degree – 要创建的多项式函数的次数

返回:

lambda 函数列表

dowhy.utils.regression.generate_moment_function(W, g)[source]#

生成并返回平均因果效应的矩函数 m(W,g) = g(1,W) - g(0,W)

dowhy.utils.regression.get_numeric_features(X)[source]#

查找数据集中的数值特征列

参数:

X – pandas dataframe

returns: 数值特征索引列表

模块内容#