【问题标题】:Importing any function from an R package into python将 R 包中的任何函数导入 python
【发布时间】:2019-12-24 07:37:30
【问题描述】:

在使用 Python 的 rpy2 库与 R 一起工作时。我在尝试导入 bnlearn 包的函数时收到以下错误消息

# Using R inside python
import rpy2
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
from rpy2.robjects.packages import importr
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)

# Install packages
packnames = ('visNetwork', 'bnlearn')
utils.install_packages(StrVector(packnames))

# Load packages
visNetwork = importr('visNetwork')
bnlearn = importr('bnlearn')

tabu = bnlearn.tabu
fit = bn.learn.bn.fit

出现错误:

AttributeError: module 'bnlearn' has no attribute 'bn'

【问题讨论】:

    标签: python r rpy2 bnlearn


    【解决方案1】:

    在检查 bnlearn documentation 时,发现 bn 是一个类结构。所以应该检查一下有问题的对象的所有属性,即运行:

    bnlearn.__dict__['_rpy2r']
    

    之后,您应该会得到与下一个类似的输出,您可以在其中找到如何导入 bnlearn 的每个属性:

    ...
    ...
    'bn_boot': 'bn.boot',
      'bn_cv': 'bn.cv',
      'bn_cv_algorithm': 'bn.cv.algorithm',
      'bn_cv_structure': 'bn.cv.structure',
      'bn_fit': 'bn.fit',
      'bn_fit_backend': 'bn.fit.backend',
      'bn_fit_backend_continuous': 'bn.fit.backend.continuous',
      'bn_fit_backend_discrete': 'bn.fit.backend.discrete',
      'bn_fit_backend_mixedcg': 'bn.fit.backend.mixedcg',
      'bn_fit_barchart': 'bn.fit.barchart',
      'bn_fit_dotplot': 'bn.fit.dotplot',
    ...
    ...
    

    然后,运行以下命令将解决问题

    bn_fit = bnlearn.bn_fit
    

    现在,例如,您可以运行贝叶斯网络:

    structure = tabu(datos, score = "loglik-g")
    bn_mod = bn_fit(structure, data = datos, method = "mle")
    

    一般来说,这种方法解决了通过 rpy2 包将任何函数从 R 包导入 Python 的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 2022-01-18
      • 2014-06-13
      • 1970-01-01
      • 2017-01-04
      相关资源
      最近更新 更多