63 lines
1.3 KiB
Python
63 lines
1.3 KiB
Python
|
|
import torch
|
||
|
|
import numpy as np
|
||
|
|
|
||
|
|
data = [[1,2],[3,4]]
|
||
|
|
x_data = torch.tensor(data)
|
||
|
|
|
||
|
|
print(x_data)
|
||
|
|
|
||
|
|
np_array = np.array(data)
|
||
|
|
x_np = torch.from_numpy(np_array)
|
||
|
|
|
||
|
|
|
||
|
|
x_ones = torch.ones_like(x_data)
|
||
|
|
print(f"Ones Tensor: \n {x_ones}\n")
|
||
|
|
print(x_ones.dtype)
|
||
|
|
|
||
|
|
x_rand = torch.rand_like(x_data, dtype=torch.float)
|
||
|
|
print(f"Random Tensor: \n {x_rand} \n")
|
||
|
|
print(x_rand.dtype)
|
||
|
|
|
||
|
|
shape=(2, 3)
|
||
|
|
rand_tensor = torch.rand(shape)
|
||
|
|
ones_tensor = torch.ones(shape)
|
||
|
|
zeros_tensor = torch.zeros(shape)
|
||
|
|
|
||
|
|
print(f"Random Tensor: \n {rand_tensor} \n")
|
||
|
|
print(f"Ones Tensor: \n {ones_tensor} \n")
|
||
|
|
print(f"Zeros Tensor: \n {zeros_tensor} \n")
|
||
|
|
|
||
|
|
|
||
|
|
tensor = torch.rand(3, 4)
|
||
|
|
print(f"Shape of tensor: {tensor.shape}")
|
||
|
|
print(f"Datatype of tensor: {tensor.dtype}")
|
||
|
|
print(f"Device tensor is stored on: {tensor.device}")
|
||
|
|
|
||
|
|
tensor = torch.ones(4, 4)
|
||
|
|
if torch.cuda.is_available():
|
||
|
|
tensor = tensor.to("cuda")
|
||
|
|
|
||
|
|
print(f"First row: {tensor[0]}")
|
||
|
|
print(f"First column: {tensor[:, 0]}")
|
||
|
|
print(f"Last Column: {tensor[..., -1]}")
|
||
|
|
tensor[:, 1] = 0
|
||
|
|
print(tensor)
|
||
|
|
|
||
|
|
t1 = torch.cat([tensor, tensor, tensor], dim=1)
|
||
|
|
print(t1)
|
||
|
|
|
||
|
|
|
||
|
|
y1 = tensor @ tensor.T
|
||
|
|
y2 = tensor.matmul(tensor.T)
|
||
|
|
print(y1)
|
||
|
|
print(y2)
|
||
|
|
y3 = torch.rand_like(y1)
|
||
|
|
torch.matmul(tensor, tensor.T, out=y3)
|
||
|
|
print(y3)
|
||
|
|
|
||
|
|
print(y3.cpu().numpy())
|
||
|
|
|
||
|
|
agg = y3.sum()
|
||
|
|
print(agg)
|
||
|
|
print(agg.item())
|