在Python中访问R用户定义的函数

时间:2017-04-17 15:06:59

标签: python r function rpy2

所以我需要使用交叉验证来进行主成分回归,而我在Python中找不到可以这样做的包。我编写了自己的PCR类但是在针对R&P的pls软件包进行测试时,它的性能显着更差,并且在高维数据(~50000个特性)上要慢很多,我仍然不确定为什么,但这是另一个问题。因为我的所有其他代码都在python中,并且为了节省时间,我决定最好的方法可能只能编写一个利用R中的PLS包的R函数。这是函数:

R_pls <-function(X_train,y_train,X_test){
  library(pls)
  X<-as.matrix(X_train)
  y<-as.matrix(y_train)
  tdata<-data.frame(y,X=I(X))
  REGmodel <- pcr(y~X,scale=FALSE,data=tdata,validation="CV")
  B<-RMSEP(REGmodel)
  C<-B[[1]]
  q<-length(C)
  degs<-c(1:q)
  allvals<-C[degs%%2==0]
  allvals<-allvals[-1]
  comps<-which.min(allvals)
  xt<-as.matrix(X_test)
  ndata<-data.frame(X=I(xt))
  ypred_test<-as.data.frame(predict(REGmodel,ncomp=comps,newdata=ndata,se.fit=TRUE))
  ntdata<-data.frame(X=I(X))
  ypred_train<-as.data.frame(predict(REGmodel,ncomp=comps,newdata=ntdata,se.fit=TRUE))
  data_out=list(ypred_test=ypred_test,ypred_train=ypred_train)
  return(data_)
}

所以我找到了很多关于如何访问R内置函数的信息,但是对于这种情况却找不到任何东西。所以我把以下内容捆绑在一起:

import rpy2.robjects as ro
prs=ro('R_pls')

其中R_pls是上面的R函数。这会产生

TypeError: 'module' object is not callable.

我知道如何让这个工作起作用,或者如果可能有更好的方法,我愿意接受建议。

谢谢

1 个答案:

答案 0 :(得分:3)

考虑使用rpy2&{39} SignatureTranslatedAnonymousPackage (STAP)将包含R的用户定义函数作为包导入:

from rpy2.robjects.numpy2ri import numpy2ri, pandas2ri
from rpy2.robjects.packages import STAP
# for rpy2 < 2.6.1
# from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP    

r_fct_string = """    
R_pls <- function(X_train, y_train, X_test){
  library(pls)

  X <- as.matrix(X_train)
  y <- as.matrix(y_train)
  xt <- as.matrix(X_test)

  tdata <- data.frame(y,X=I(X))
  REGmodel <- pls::pcr(y~X,scale=FALSE,data=tdata,validation="CV")
  B <- RMSEP(REGmodel)
  C <- B[[1]]
  q <- length(C)
  degs <- c(1:q)
  allvals <- C[degs%%2==0]
  allvals <- allvals[-1]
  comps <- which.min(allvals)
  ndata <- data.frame(X=I(xt))

  ypred_test <- as.data.frame(predict(REGmodel,ncomp=comps,newdata=ndata,se.fit=TRUE))
  ntdata <- data.frame(X=I(X))
  ypred_train <- as.data.frame(predict(REGmodel,ncomp=comps,newdata=ntdata,se.fit=TRUE))
  data_out <- list(ypred_test=ypred_test, ypred_train=ypred_train)

  return(data_out)
}
"""

r_pkg = STAP(r_fct_string, "r_pkg")

# CONVERT PYTHON NUMPY MATRICES TO R OBJECTS
r_X_train, r_y_train, r_X_test = map(numpy2ri, py_X_train, py_y_train, py_X_test)

# PASS R OBJECTS INTO FUNCTION (WILL NEED TO EXTRACT DFs FROM RESULT)
p_res = r_pkg.R_pls(r_X_train, r_y_train, r_X_test)

或者,如果函数保存在单独的.R脚本中,则可以将函数作为@agstudy显示here来源,然后像任何Python函数一样调用它。

import rpy2.robjects as ro
robjects.r('''source('my_R_pls_func.r')''')

r_pls = ro.globalenv['R_pls']

# CONVERT PYTHON NUMPY MATRICES TO R OBJECTS
r_X_train, r_y_train, r_X_test = map(numpy2ri, py_X_train, py_y_train, py_X_test)

# PASS R OBJECTS INTO FUNCTION (WILL NEED TO EXTRACT DFs FROM RESULT)
p_res = r_pls(r_X_train, r_y_train, r_X_test)