PyTorch Tensors from Data
Tensors from data turn nested lists and tuples into tensors that keep the same rows. Each inner list becomes one row of the table.
Nested lists become a table
Each inner list becomes one row. Both rows here hold two values.
import torch
grid = torch.tensor([[2, 4], [6, 8]])
print(grid)Tuples work too
Round brackets make a tuple in Python. A tuple becomes a tensor in the same way.
pair = torch.tensor((7, 9))
print(pair)Mixed rows become decimals
A row can mix whole numbers and decimals. The tensor then stores every value as a decimal.
mixed = torch.tensor([[1, 2.5], [3, 4.5]])
print(mixed)
print(mixed.dtype)A ragged list fails
Rows of different lengths are called ragged. This code fails with ValueError, because the second row is shorter.
bad = torch.tensor([[1, 2], [3]])Example
import torch
temps = torch.tensor(
[
[18.0, 24.0],
[17.0, 23.0],
[19.0, 25.0],
[20.0, 26.0],
[21.0, 27.0],
[22.0, 28.0],
[19.0, 24.0],
]
)
print(temps)
print(temps.shape)Key points
- A nested list becomes a table with one row per inner list
- Use tuples as tensor data in the same way as lists
- Mixed rows: one decimal in the data makes the whole tensor float32
- Ragged: rows with different lengths in one list
- Use equal lengths for every row in a nested list
In this example, the program lists seven rows of temperatures. Each row holds a low and a high for one day. torch.tensor turns the nested list into one table. The table prints with seven rows and two columns. The last line prints the shape, torch.Size([7, 2]).
Note
A ragged list raises ValueError, and the message states the expected length and the length it got.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Python Playground
Exercise
Why does torch.tensor([[1, 2], [3]]) fail?