44 lines
1 KiB
Python
44 lines
1 KiB
Python
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]}")
|