因此,我需要使用交叉验证来进行主成分回归,但在Python中找不到这样做的包。我写了我自己的PCR类,但当用R的pls包进行测试时,它的表现明显更差,在高维数据(约50000个特征)上慢得多,我仍然不知道为什么,但这是另一个问题。因为我的其他代码都是用python编写的,为了节省时间,我决定最好的方法就是编写一个R函数,该函数利用R中的PLS包
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内置函数的信息,但是对于这种情况,我找不到任何东西。所以我打了个平手:
^{pr2}$其中R_pls是上面的R函数。这就产生了
TypeError: 'module' object is not callable.
如果有更好的方法,我愿意接受建议。在
谢谢
考虑将abitrary R用户定义函数作为带有rpy2的SignatureTranslatedAnonymousPackage (STAP)的包导入:
或者,您可以将函数作为@agstudy显示的here源代码,如果函数保存在单独的.R脚本中,则可以像任何Python函数一样调用它。在
^{pr2}$相关问题 更多 >
编程相关推荐