【问题标题】:How to pass a R function as argument using rpy2 in a Python code如何在 Python 代码中使用 rpy2 将 R 函数作为参数传递
【发布时间】:2017-01-26 04:08:48
【问题描述】:

我正在尝试为出色的 NMF 包创建 Python 接口 - https://cran.r-project.org/web/packages/NMF/NMF.pdf(因为它比 Python 选项灵活得多)。到目前为止一切顺利。

我想出了这样的事情:

# Python rpy2
__NMF = importr("NMF")
n_comp_R = robjects.IntVector(n_components)
nmf_ro = self.__NMF.nmf(data, n_comp_R, methods, self.seed, nrun=10)

它就像一个魅力。 Methods 是我可以使用的可能算法的列表:

nmf算法()

[1]“深色”“KL”“李”“Frobenius”“偏移”

[6]“nsNMF”“ls-nmf”“pe-nmf”“siNMF”“snmf/r”

[11] "snmf/l"

其他可能性是使用自定义算法,如 NMF 文档中所述

# R code
my.algorithm <- function(x, seed, param.1, param.2) {
    # do something with starting point ...
    # return updated starting point
    return(seed)
} 
res <- nmf(data, n_comp, my.algorithm)

如何使用rpy2 重现此内容?

我尝试过类似的方法:

import rpy2.robjects as robjects

my_algorithm = robjects.r('''
function (x, seed, scale.factor = 1) 
{
    pca <- prcomp(t(x), retx = TRUE)
    factorization.rank <- nbasis(seed)
    cat(seed)
    basis(seed) <- abs(pca$rotation[, 1:factorization.rank])
    coef(seed) <- t(abs(pca$x[, 1:factorization.rank]))/scale.factor
    return(seed)
    }
''')
nmf_ro = __NMF.nmf(data, n_comp_R, my_algorithm.r_repr(), nrun=1)

但它并没有产生魔法 =(

NMF 算法 - 键“key=function (x, seed, scale.factor >= 1) 没有匹配条目

{

pca

factorization.rank

猫(种子)

基础(种子)

coef(seed)

返回(种子)

}”在注册表中。

使用以下之一:'brunet'、'Frobenius'、'KL'、'lee'、'ls-nmf'、'.M#brunet'、'nsNMF'、'offset'、'pe-nmf'、 '.R#brunet'、'.R#lee'、'.R#nsNMF'、'.R#offset'、'siNMF'、'.siNMF'、'snmf/l'、'snmf/r'。

warnings.warn(x, RRuntimeWarning)

我想知道是否有人可以在这里帮助我?

【问题讨论】:

    标签: python r machine-learning rpy2 nmf


    【解决方案1】:

    原提问者had his question answered on the NMF project on Github。如那里所述,您将新算法定义为一个函数,然后使用 setNMFMethod 将该函数添加到执行非负矩阵分解的算法的注册表中,然后您可以按名称调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      相关资源
      最近更新 更多