From 1cd7176f24abb95b484c8aaea25a7f63754269d3 Mon Sep 17 00:00:00 2001 From: Ayo Date: Tue, 2 Sep 2025 22:29:14 +0200 Subject: [PATCH] feat: add tensors --- 01-tensors.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 ++ 2 files changed, 46 insertions(+) create mode 100644 01-tensors.py diff --git a/01-tensors.py b/01-tensors.py new file mode 100644 index 0000000..46455bf --- /dev/null +++ b/01-tensors.py @@ -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]}") diff --git a/README.md b/README.md index 0a1f0f6..79c7d20 100644 --- a/README.md +++ b/README.md @@ -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)