这篇文章与我之前的How to define a Python Class which uses R code, but called from rTorch?有关。
我偶然发现了R (https://torch.mlverse.org/docs/index.html)中的torch包,它允许定义DataSet类定义。但是,我还需要能够在Python语言中定义像class MyModelClass(torch.nn.Module)这样的模型类。这在R中的torch包中是可能的吗?
当我尝试用reticulate来做这件事时,它不起作用--有一些冲突,比如
ImportError: /User/homes/mreichstein/miniconda3/envs/r-torch/lib/python3.6/site-packages/torch/lib/libtorch_python.so: undefined symbol: _ZTINSt6thread6_StateE这也没有多大意义,因为torch没有包装Python。
但它失去了rTorch所具有的很多灵活性(但请参阅上面这篇文章中的问题)。谢谢你的帮助!马库斯
发布于 2020-12-29 10:25:41
您可以直接使用R的torch包来完成此任务,该包看起来相当全面,至少对于基本任务是这样。
神经网络
Here是一个创建nn.Sequential的示例,如下所示:
library(torch)
model <- nn_sequential(
nn_linear(D_in, H),
nn_relu(),
nn_linear(H, D_out)
)下面是一个自定义的nn_module (也称为torch.nn.Module),它是一个简单的密集(torch.nn.Linear)层(source):
library(torch)
# creates example tensors. x requires_grad = TRUE tells that
# we are going to take derivatives over it.
dense <- nn_module(
clasname = "dense",
# the initialize function tuns whenever we instantiate the model
initialize = function(in_features, out_features) {
# just for you to see when this function is called
cat("Calling initialize!")
# we use nn_parameter to indicate that those tensors are special
# and should be treated as parameters by `nn_module`.
self$w <- nn_parameter(torch_randn(in_features, out_features))
self$b <- nn_parameter(torch_zeros(out_features))
},
# this function is called whenever we call our model on input.
forward = function(x) {
cat("Calling forward!")
torch_mm(x, self$w) + self$b
}
)
model <- dense(3, 1)另一个示例,这次使用torch.nn.Linear层创建神经网络(source):
two_layer_net <- nn_module(
"two_layer_net",
initialize = function(D_in, H, D_out) {
self$linear1 <- nn_linear(D_in, H)
self$linear2 <- nn_linear(H, D_out)
},
forward = function(x) {
x %>%
self$linear1() %>%
nnf_relu() %>%
self$linear2()
}
)还有其他资源,比如here (使用流控制和权重共享)。
其他
看一下the reference,似乎大多数层都已经提供了(没注意到转换器层,但这是次要的)。
据我所知,神经网络的基本模块,它们的训练等都是现成的(即使是JIT,因此应该可以在语言之间共享)。
https://stackoverflow.com/questions/65427461
复制相似问题