如何在 Python 代码中使用 rpy2 将 R 函数作为参数传递

How to pass a R function as argument using rpy2 in a Python code

我正在尝试为出色的 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)

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

nmfAlgorithm()

[1] "brunet" "KL" "lee" "Frobenius" "offset"

[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 algorithm - No matching entry for key “key=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)

}” in the registry.

Use one of: '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)

不知是否有人可以帮助我?

原提问者had his question answered on the NMF project on Github. As described there, you define your new algorithm as a function, then use setNMFMethod将该函数添加到执行非负矩阵分解算法的注册表中,然后您可以通过名称调用它。