interfacing Python and Torch7(Lua) via shared library

前端 未结 3 553
盖世英雄少女心
盖世英雄少女心 2020-12-21 04:05

I am trying to pass data (arrays) between python and lua and I want to manipulate the data in lua using the Torch7 framework. I figured this can best be done through C, sin

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-21 05:05

    For exchanging data between python/numpy and lua/torch, you could try a library named "lutorpy". It does exactly what you are trying to do, share the memory and only pass the pointer with "asNumpyArray()" method.

    import lutorpy as lua
    import numpy as np
    
    ## run lua code in python with minimal modification:  replace ":" to "._"
    t = torch.DoubleTensor(10,3)
    print(t._size()) # the corresponding lua version is t:size()
    
    ## convert torch tensor to numpy array
    ### Note: the underlying object are sharing the same memory, so the conversion is instant
    arr = t.asNumpyArray()
    print(arr.shape)
    
    ## or, you can convert numpy array to torch tensor
    xn = np.random.randn(100)
    ## convert the numpy array into torch tensor
    xt = torch.fromNumpyArray(xn)
    

提交回复
热议问题