feat: add tensors

This commit is contained in:
Ayo Ayco 2025-09-02 22:29:14 +02:00
parent fbeb9e14ad
commit 1cd7176f24
2 changed files with 46 additions and 0 deletions

44
01-tensors.py Normal file
View file

@ -0,0 +1,44 @@
import torch
import numpy as np
# initialize a tensor directly as data
data = [[1,2],[3,4]]
x_data = torch.tensor(data).to('xpu')
print(x_data)
# from a numpy array
arr = np.array(data)
x_np = torch.from_numpy(arr).to('xpu')
print(x_np)
# from another tensor (could override the shape, datatype)
x_ones = torch.ones_like(x_data) # retains properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides datatype
print(f"Random Tensor: \n {x_rand} \n")
# use `shape` to define dimentions
shape = (3,5)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random: \n {rand_tensor} \n")
print(f"Ones: \n {ones_tensor} \n")
print(f"Zeros: \n {zeros_tensor} \n")
# tensors have attributes
tensor_attr = torch.rand(3,4).to('xpu')
# print(f"Shape: {tensor_attr.shape}")
# print(f"Datatype: {tensor_attr.dtype}")
# print(f"Device: {tensor_attr.device}")
# indexing & slicing
tensor = torch.ones(4,4).to('xpu')
print(f"First row: {tensor[0]}")

View file

@ -38,3 +38,5 @@ $ torch.xpu.get_device_name()
## Links
- [Get started with PyTorch locally](https://pytorch.org/get-started/locally/)
- [Getting started with Tensors](https://docs.pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html)
- [torch operations](https://docs.pytorch.org/docs/stable/torch.html)