带网状结构的 R 中的 scikit-learn

scikit-learn in R with reticulate

我正在尝试使用 R 中的 reticulate 包。有个不错的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。 (是的,我知道 R 可以完美地做到这一点,但我现在只是在测试一些东西...)


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'

显式传递参数不起作用。

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'

有什么想法吗?

就像正常 Python/Scikit 一样,您需要先初始化模型对象,然后才能 fit 它。

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