I'm not sure how to reproduce the following R code in python using rpy2. I'm not sure how to implement the R syntax type.measure="class" when training the model, and the last two lines of the R code are missing in my attempt in 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)
And the unfinished python code:
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")
If the parameter in the R function is defined in the function's signature, rpy2's importr
will translate the dot into an underscore. Otherwise, the python operator **
can be used (see http://rpy2.readthedocs.io/en/version_2.8.x/robjects_functions.html#functions)