python - 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?
解决方案
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
推荐阅读
- javascript - 迭代一个对象数组并在 es6 中分离比较日期
- python - 如何摆脱使用代码查找最近邻居时遇到的此错误?
- r - r中的卡方测试,保留行名
- docker - 使用 ssh 的自定义字体设置 apache guacamole
- f# - F# 类型提供程序 FSharp,Data.SqlClient 目标 .NetStandard 2.0 在使用命令行中的 dotNet 构建时失败,但在 Visual Studion 2019 中成功
- objective-c - 在使用目标/选择器模式进行回调的 Objective-C 方法中使用 NSBlockOperation?
- mysql - MySQL / MariaDB LOAD DATA INFILE with CSV 没有 id 列(主键)并尝试通过 DBMS 自动递增无法识别 SET 命令
- javascript - 如何将 div x 保持在 img 的右侧,它当前覆盖在使用绝对位置上?
- deep-learning - ZMQ python编程
- javascript - JS中对对象/数组的最快操作