在 R 包 "torch" 中定义 Torch Class

Defining a Torch Class in R package "torch"

这个post与我之前的How to define a Python Class which uses R code, but called from rTorch?有关。

我在 R (https://torch.mlverse.org/docs/index.html) 中遇到了 torch 包,它允许定义数据集 class 定义。然而,我还需要能够定义一个模型 class,例如 Python 中的 class MyModelClass(torch.nn.Module)。这在 R 中的火炬包中可能吗?

当我尝试用 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 所具有的很多灵活性(但请参阅上面 post 中我的问题)。 谢谢你的帮助! 马库斯

您可以直接使用 R 的 torch 程序包来做到这一点,至少对于基本任务而言,它看起来相当全面。

神经网络

Here 是如何创建 nn.Sequential 的示例:

library(torch)

model <- nn_sequential(
    nn_linear(D_in, H),
    nn_relu(),
    nn_linear(H, D_out)
)

下面是一个自定义 nn_module (a.k.a. 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,所以语言之间的共享应该是可能的)。