PyTorch Creating Tensors
Creating a tensor turns a Python list into a tensor with torch.tensor. A tensor can be a row, a table, or a stack of tables.
From a list
Rank counts the directions of a tensor. A row has rank one.
import torch
row = torch.tensor([4, 8, 15])
print(row)A table from nested lists
A list of lists makes a table. A table has rank two.
table = torch.tensor([[1, 2], [3, 4]])
print(table)A stack of tables
A list of tables makes a stack. A stack has rank three.
stack = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(stack)Example
import torch
scores = torch.tensor([[85, 90, 78], [92, 88, 95]])
print(scores)Key points
- A tensor holds the same numbers in the same rows as the list it came from
- Rank: the count of directions a tensor spreads in
- Rank one: a row of values
- Rank two: a table of rows and columns
- Rank three: a stack of tables
In this example, the program builds one nested list of quiz scores. Each inner list is one student and three quiz scores. torch.tensor turns the nested list into a table. The print line shows the table with two rows.
Note
The tensor keeps whole numbers as whole numbers and decimals as decimals.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
What does a list of lists become with torch.tensor?