22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Output

tensor([[1., 2., 1.],

[1., 1., 1.]])

tensor([[1., 3., 1., 1., 1., 1.]])

Output

UserWarning: To copy construct from a tensor, it is

recommended to use sourceTensor.clone().detach() or

sourceTensor.clone().detach().requires_grad_(True),

rather than tensor.new_tensor(sourceTensor).

"""Entry point for launching an IPython kernel.

It seems that PyTorch prefers that we use clone()—together with

detach()—instead of new_tensor(). Both ways accomplish exactly the same

result, but the code below is deemed cleaner and more readable.

# Let's follow PyTorch's suggestion and use "clone" method

another_matrix = matrix.view(1, 6).clone().detach()

# Again, if we change one of its elements...

another_matrix[0, 1] = 4.

# The original tensor (matrix) is left untouched!

print(matrix)

print(another_matrix)

Output

tensor([[1., 2., 1.],

[1., 1., 1.]])

tensor([[1., 4., 1., 1., 1., 1.]])

You’re probably asking yourself: "But, what about the detach()

method—what does it do?"

It removes the tensor from the computation graph, which probably raises more

questions than it answers, right? Don’t worry, we’ll get back to it later in this

chapter.

PyTorch | 75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!