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.

Beware: The view() method only returns a tensor with the

desired shape that shares the underlying data with the original

tensor—it DOES NOT create a new, independent, tensor!

The reshape() method may or may not create a copy! The

reasons behind this apparently weird behavior are beyond the

scope of this section, but this behavior is the reason why view()

is preferred.

# We get a tensor with a different shape but it still is

# the SAME tensor

same_matrix = matrix.view(1, 6)

# If we change one of its elements...

same_matrix[0, 1] = 2.

# It changes both variables: matrix and same_matrix

print(matrix)

print(same_matrix)

Output

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

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

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

If you want to copy all data, that is, duplicate the data in memory, you may use

either its new_tensor() or clone() methods.

# We can use "new_tensor" method to REALLY copy it into a new one

different_matrix = matrix.new_tensor(matrix.view(1, 6))

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

different_matrix[0, 1] = 3.

# The original tensor (matrix) is left untouched!

# But we get a "warning" from PyTorch telling us

# to use "clone()" instead!

print(matrix)

print(different_matrix)

74 | Chapter 1: A Simple Regression Problem

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

Saved successfully!

Ooh no, something went wrong!