Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling R library "randomForest" from python using rpy2

Tags:

python

r

rpy2

I would like to embed some R libraries in my python script by using rpy2. I already embedded succesfully "stats.lm", but now I would like to embed "randomForest".

import pandas as pd
from rpy2.robjects.packages import importr
from rpy2.robjects import r, pandas2ri
import rpy2.robjects as robjects

randomForest=importr('randomForest')

pandas2ri.activate()

#read data
df = pd.read_csv('train.csv',index_col=0)
rdf = pandas2ri.py2ri(df)

#check
print(type(rdf))
print(rdf)

#Random Forest
formula = 'target ~ .'
fit_full = randomForest(formula, data=rdf)

The output is:

Traceback (most recent call last):

  File "<ipython-input-5-776f4072f19e>", line 2, in <module>
    fit_full = randomForest(formula, data=rdf)

TypeError: 'InstalledSTPackage' object is not callable

I already used succesfully this package in R to model this dataset. "train.csv" is a matrix of some tens of thousand samples (rows) and about 94 columns: 93 features (class integer), 1 target (class factor). Target column has 9 classes (Class_1,...,Class_9).

----------------- EDIT -----------------

A partial solution could be to directly embed the code in a function that contains the model and prediction:

import rpy2.robjects as robjects
import rpy2
from rpy2.robjects import pandas2ri

rpy2.__version__

robjects.r('''
           f <- function() {

                    library(randomForest)

                    train <- read.csv("train.csv")
                    train1 <- train[sample(c(1:60000), 5000, replace = TRUE),2:95]

                    train1.rf <- randomForest(target ~ ., data = train1,
                                          importance = TRUE,
                                           do.trace = 100)

                    pred <- as.data.frame(predict(train1.rf, train1[1:100,1:93]))

            }
            ''')

r_f = robjects.globalenv['f']
pred=pandas2ri.ri2py(r_f())

but I'm still wondering if there is a better solution (that stores the model "train1.rf", too).

like image 364
FedRo Avatar asked Jul 17 '26 15:07

FedRo


1 Answers

This is what I was searching for:

import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
import pandas as pd
import random

pandas2ri.activate()

df = pd.read_csv('train.csv',index_col=0)



train=df.iloc[random.sample(range(1,60000), 5000),0:94]
test=df.iloc[random.sample(range(1,60000), 100),0:93]


rtrain = pandas2ri.py2ri(train)
print(rtrain)
rtest = pandas2ri.py2ri(test)
print(rtest)


robjects.r('''
           f <- function(train) {

                    library(randomForest)
                    train1.rf <- randomForest(target ~ ., data = train, importance = TRUE, do.trace = 100)

            }
            ''')
r_f = robjects.globalenv['f']
rf_model=(r_f(rtrain))


robjects.r('''
           g <- function(model,test) {

                    pred <- as.data.frame(predict(model, test))

            }
            ''')

r_g = robjects.globalenv['g']
pred=pandas2ri.ri2py(r_g(rf_model,rtest))
like image 86
FedRo Avatar answered Jul 20 '26 06:07

FedRo