3

I am trying to use the reticulate package in R. There is a good intro here, but I'm failing to make much progress. Let's say I want to do something simple like build a linear model with scikit-learn. (Yes, I know R can do this perfectly well, but I'm just testing some things now...)


library(reticulate)

# import modules
pd <- import("pandas")
np <- import("numpy")
skl_lr <- import("sklearn.linear_model")

# set up variables and response
x <- mtcars[, -1]
y <- mtcars[, 1]

# convert to python objects
pyx <- r_to_py(x)
pyy <- r_to_py(y)

# create model
skl_lr$LinearRegression$fit(pyx, pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: fit() missing 1 required positional argument: 'y'

Passing the the arguments explicitly does not work.

skl_lr$LinearRegression$fit(X = pyx, y = pyy)

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  TypeError: fit() missing 1 required positional argument: 'self'

Any ideas?

Nick Criswell
  • 1,733
  • 2
  • 16
  • 32

1 Answers1

4

Just like in normal Python/Scikit, you need to initialize a model object before you can fit it.

lr <- skl_lr$LinearRegression()
lr$fit(pyx, pyy)

lr$coef_
# [1] -0.11144048  0.01333524 -0.02148212  0.78711097 -3.71530393  0.82104075  0.31776281
# [8]  2.52022689  0.65541302 -0.19941925
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • Thanks. The problem with my attempts are very close to simple typos it seems. Happy to delete, but there aren't a ton of working examples of using `reticulate` and `scikit-learn` together so there might be some value in just having a question on it out here. – Nick Criswell Feb 15 '20 at 17:04
  • You're welcome. And re typo, I had the same thought, and came to the same conclusion - `reticulate` crossovers are new enough so that it can't hurt to have a few simple reminders in circulation. – andrew_reece Feb 15 '20 at 17:49