我在使用 rpy2 包时遇到一些问题

问题描述 投票:0回答:1

在此代码中,我无法使用普通的 robjects.r.matrix 语句将变量 cpgraph 转换为 类型。是不是因为我的图比较复杂?

这是代码

def sample_graphs(mpgraph, n_graphs=10, equal_weights=False):
    graphs = []
    if nx.is_directed_acyclic_graph(nx.DiGraph(mpgraph)):
        graphs.append((mpgraph.copy(), n_graphs))
    else:
        n_vars = mpgraph.shape[0]

        addBgKnowledge = robjects.r['addBgKnowledge']
        for _ in range(n_graphs):
            graph = mpgraph.copy()
            undirected_u, undirected_v = np.nonzero(np.triu(graph == graph.T) & (graph == 1))

            while len(undirected_u) > 0:
                selected_edge_idx = np.random.randint(0, len(undirected_u))
                u, v = undirected_u[selected_edge_idx], undirected_v[selected_edge_idx]
                if np.random.rand() < 0.5:
                    u, v = v, u

                numpy2ri.activate()
                pandas2ri.activate()

                cpgraph = robjects.r.matrix(graph, nrow=n_vars, ncol=n_vars)
                print(cpgraph)
                print(type(cpgraph))
                cpgraph.rownames = robjects.StrVector([str(i) for i in range(n_vars)])
                cpgraph.colnames = robjects.StrVector([str(i) for i in range(n_vars)])
                cpgraph = r_as(cpgraph, 'graphNEL')

                numpy2ri.deactivate()
                pandas2ri.deactivate()

                graph = r_as(addBgKnowledge(cpgraph, x=[str(u)], y=[str(v)]), 'matrix').astype(int)

                undirected_u, undirected_v = np.nonzero(np.triu(graph == graph.T) & (graph == 1))


            found = False

            for idx, (comp_graph, weight) in enumerate(graphs):
                if (comp_graph == graph).all():
                    graphs[idx] = (graph, weight + 1)
                    found = True
                    break

            if not found:
                graphs.append((graph, 1))

    if equal_weights:
        graphs = [(graph, 1 / len(graphs)) for graph, _ in graphs]
    else:
        graphs = [(graph, w / n_graphs) for graph, w in graphs]
    return graphs

我尝试编写一段单独的代码来检查rpy2包的可用性,以证明它是可用的。

import rpy2.robjects as robjects
from rpy2.robjects import numpy2ri
import numpy as np
import networkx as nx

numpy2ri.activate()
data = np.array(\[1, 2, 3, 4\])
r_matrix = robjects.r.matrix(data, nrow=2, ncol=2)
print(type(r_matrix))

print(nx.__version__)

输出结果为: 2.5

python rpy2
1个回答
0
投票

不鼓励使用

.activate()
方法。更喜欢本地转换器(请参阅此处doc)。

除此之外,您必须确保您的Python对象

graph
可以转换为传递给R函数
matrix()
的R序列(请参阅此处的doc),或者可以直接转换为R使用 rpy2 的转换规则集的矩阵(
numpy
矩阵到 R 矩阵是
numpy2ri.converter
单独可以做到的)。
graph
似乎是
mpgraph
的副本,因此这是您必须查看的 python 类型。

© www.soinside.com 2019 - 2024. All rights reserved.