用rpy2在python中重现R glmnet代码

时间:2017-05-25 10:04:07

标签: python r rpy2 glmnet

我不确定如何使用rpy2在python中重现以下R代码。我不确定如何在训练模型时实现R语法 type.measure =" class" ,并且我的R代码的最后两行丢失了在python中尝试。

library("foreach")
library("glmnet")
library(datasets)
data(iris)

y <- as.numeric(iris[,5])
X <- iris[1:4]

model_lambda <- cv.glmnet(as.matrix(X), as.factor(y), alpha=0,
family="multinomial", type.measure="class")
best_s  <- model_lambda$lambda.1se
prediction <- predict(model_lambda,newx=as.matrix(X), type="class" , s=best_s)

未完成的python代码:

import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
importr('foreach')
glmnet = importr('glmnet')
import rpy2.robjects.numpy2ri as numpy2ri
numpy2ri.activate()

from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
model_lambda = glmnet.cv_glmnet(X, robjects.FactorVector(y), alpha=1, family="multinomial")

1 个答案:

答案 0 :(得分:2)

如果R函数中的参数是在函数签名中定义的,则rpy2的importr会将点转换为下划线。否则,可以使用python运算符**(请参阅http://rpy2.readthedocs.io/en/version_2.8.x/robjects_functions.html#functions