Lightning AI Studios: Never set up a local environment again →

Log in or create a free account to track your progress and access additional course materials  

2.3 How Do We Use Tensors in PyTorch?


What we covered in this video lecture

In this video, we went over ten fundamental tensor usage examples, from creating tensors in PyTorch to multiplying two matrices (rank-2 tensors). We will refer to these operations many times when we implement neural networks throughout this course!

Additional resources if you want to learn more

PyTorch tensors have tons of advanced functionality. If you are curious about additional features that we didn’t discuss in this lecture, you can check out the full tensor API documentation here — however, I recommend bookmarking it for later after we trained our first neural networks!

Log in or create a free account to access:

  • Quizzes
  • Completion badges
  • Progress tracking
  • Additional downloadable content
  • Additional AI education resources
  • Notifications when new units are released
  • Free cloud computing credits

Quiz: 2.3 How Do We Use Tensors in PyTorch?

Which of the The following commands creates a 4×2 tensor? Check all that apply.

Incorrect. Hint: check the number of rows and columns using a.shape.

Correct. The torch.tensor() call creates a 2×4 matrix at first, but via .T we transposed it to a 4×2 matrix.

Correct. Each of the four inner lists represents a row of the 4×2 tensor.

Incorrect. Executing this code will yield a TypeError. Hint: Check if you forgot any paranthesis or brackets.

There are at least 2 ways we can convert a NumPy array into a PyTorch tensor. Suppose a = np.array([1, 2]) is a NumPy array. Which of the following methods are valid ways to obtain a PyTorch tensor from this array?

Correct. In this case, PyTorch makes copies the contents of the NumPy array into a tensor format.

Incorrect. This syntax is not correct, but you are close.

Correct. In this case, PyTorch creates a tensor that shares the same memory as the NumPy array. In terms of memory usage, this is more efficient than torch.tensor(a)

Correct. We haven’t covered this in the lecture, but this is another way to create a tensor by calling the torch.Tensor class directly instead of using the tensor function torch.tensor. However, in practice it is recommended to use torch.tensor as it carries out some additional checks under the hood.

Please answer all questions to proceed.
Watch Video 1

Unit 2.3

Follow along in a Lightning Studio

DL Fundamentals 2: Tensors and PyTorch

Launch Studio →
Questions or Feedback?

Join the Discussion