WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

PyTorch · Basic · question 4 of 100

How do you create a tensor in PyTorch? Provide an example.?

📕 Buy this interview preparation book: 100 PyTorch questions & answers — PDF + EPUB for $5

In PyTorch, a tensor is a multi-dimensional array used for storing and manipulating numeric data. To create a tensor in PyTorch, we can use the ‘torch.Tensor()‘ constructor, which takes a sequence of data as input and creates a tensor out of it. Here’s an example to create a tensor of rank 2 (a matrix) with dimensions 3x2:

import torch

my_tensor = torch.Tensor([[1, 2], [3, 4], [5, 6]])
print(my_tensor)

Output:
tensor([[1., 2.],
        [3., 4.],
        [5., 6.]])

In this example, we first import the PyTorch library using ‘import torch‘. We then create a 2D tensor of size 3x2 by passing a list of lists containing the data to the ‘torch.Tensor()‘ constructor. We assign the resulting tensor to the variable ‘my_tensor‘. Finally, we use the ‘print()‘ function to display the tensor on the screen.

There are other ways to create tensors in PyTorch, such as using ‘torch.zeros()‘, ‘torch.ones()‘, ‘torch.arange()‘, and so on. These functions provide convenient ways to create tensors with specific values or dimensions. Additionally, we can also create tensors from existing data, such as NumPy arrays, using the ‘torch.from_numpy()‘ method or convert tensors to NumPy arrays using the ‘.numpy()‘ method.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic PyTorch interview — then scores it.
📞 Practice PyTorch — free 15 min
📕 Buy this interview preparation book: 100 PyTorch questions & answers — PDF + EPUB for $5

All 100 PyTorch questions · All topics