简体   繁体   中英

Convert Torch Lua into Numpy Python

Am looking to convert some Lua Torch code into numpy Python. I google for find some documentations, but it still unclear.

I found this. https://nn.readthedocs.io/en/rtd/index.html

Wondering if there is any mapping between Lua Torch functions and numpy functions ?

Thanks

You could try Lutorpy , a python library for bridging lua/torch with python/numpy.

Here is an example of conversion:

-- lua code                             # python code (with lutorpy)
--                                      import lutorpy as lua
require "nn"                    ===>    require("nn")
model = nn.Sequential()         ===>    model = nn.Sequential()
-- use ":" to access add        ===>    # use "._" to access add
model:add(nn.Linear(10, 3))     ===>    model._add(nn.Linear(10, 3))
--                                      import numpy as np
x = torch.Tensor(10):zero()     ===>    arr = np.zeros(10)
-- torch style(painful?)        ===>    # numpy style(elegent?) 
x:narrow(1, 2, 6):fill(1)       ===>    arr[1:7] = 1
--                                      # convert numpy array to a torch tensor
--                                      x = torch.fromNumpyArray(arr)
--                                      # or you can still use torch style
x:narrow(1, 7, 2):fill(2)       ===>    x._narrow(1, 7, 2)._fill(2)
-- 1-based index                ===>    # 0-based index
x[10] = 3                       ===>    x[9] = 3
y = model:forward(x)            ===>    y = model._forward(x)
--                                      # you can convert y to a numpy array
--                                      yArr = y.asNumpyArray()

For more information, you could goto the github page of lutorpy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM