简体   繁体   中英

PyTorch: How to append tensors into a list using loops

I have the following code which outputs 2 arrays in a list:

arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]])

arr_split = np.array_split(arr1,
                           indices_or_sections = 2,
                           axis = 0)

arr_split

Output:

[array([[1., 2., 3.],
        [4., 5., 6.]]), array([[7., 8., 9.]])]

How do I cast these 2 arrays into PyTorch tensors and put them into a list using for (or while ) loops, so that they look like this:

[tensor([[1., 2., 3.],
         [4., 5., 6.]], dtype=torch.float64),
tensor([[7., 8., 9.]], dtype=torch.float64)]

Many thanks in advance!

Better you convert it to tensor at first place and then you can usetorch.Tensor.split

arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]])
t_arr1 = torch.from_numpy(arr1)

t_arr1.split(split_size=2)
(tensor([[1., 2., 3.],
        [4., 5., 6.]], dtype=torch.float64), 
 tensor([[7., 8., 9.]], dtype=torch.float64))

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