首页 > 解决方案 > scikit-learn in R with reticulate

问题描述

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?

标签: pythonrscikit-learnreticulate

解决方案


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

推荐阅读