1
我不確定如何在Python中使用rpy2重現以下R代碼。我不知道如何在訓練模型時執行R語法type.measure =「class」,並且在我嘗試使用python時,R代碼的最後兩行缺失。在Python中使用rpy2重現R glmnet代碼
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")