首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在R包" Torch“中定义torch类

在R包" Torch“中定义torch类
EN

Stack Overflow用户
提问于 2020-12-24 00:17:02
回答 1查看 175关注 0票数 3

这篇文章与我之前的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来做这件事时,它不起作用--有一些冲突,比如

代码语言:javascript
复制
  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所具有的很多灵活性(但请参阅上面这篇文章中的问题)。谢谢你的帮助!马库斯

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-29 10:25:41

您可以直接使用R的torch包来完成此任务,该包看起来相当全面,至少对于基本任务是这样。

神经网络

Here是一个创建nn.Sequential的示例,如下所示:

代码语言:javascript
复制
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):

代码语言:javascript
复制
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):

代码语言:javascript
复制
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,因此应该可以在语言之间共享)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65427461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档