Compute matrices in PyTorch

Asked 1 years ago, Updated 1 years ago, 79 views

I'm using PyTorch to learn in-depth learning.
I use numpy's np.tile and np.reshape in the forward calculation, but if I convert the Tensor type to numpy's ndarray type, the requirements_grad information will be lost and I cannot learn.

Is there a way to do things like tile while still in the Tensor type?

Or is it not possible to calculate with numpy while keeping the requirements_grad information?

python numpy deep-learning pytorch

2022-09-30 21:43

1 Answers

How do you like this?

#!/usr/bin/env python

import torch

# tile
x=torch.tensor([[1,2], [3,4]], dtype=torch.float32)
x.requires_grad_()
print(x)
x = x.repeat(2,3)
print(x)

# reshape
x=torch.tensor([1,2], [3,4], [5,6]], dtype=torch.float32)
x.requires_grad_()
print(x)
x = x.view(2, -1)
print(x)

The output is as follows:

luna:~%./testu1.py
US>tensor([1., 2.],
        [3.,4.]], requires_grad=True)
US>tensor([[1., 2., 1., 2., 1., 2.],
        [3., 4., 3., 4., 3., 4.],
        [1., 2., 1., 2., 1., 2.],
        [3. , 4. , 3. , 4. , 3. , 4. ] , grad_fn = <RepeatBackward > )
US>tensor([1., 2.],
        [3., 4.],
        [5, 6.] , requires_grad = True )
US>tensor([1., 2., 3.],
        [4. , 5. , 6. ] , grad_fn = <ViewBackward >)


2022-09-30 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.