Pytorch Tensor

Tensor Tutorial

from data

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

from numpy array

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

其他张量

新张量保留参数张量的属性(形状、数据类型),除非显式覆盖。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

"""
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.2387, 0.1440],
        [0.6885, 0.2764]]) 
"""

属性

tensor.shape
tensor.dtype
tensor.device

操作

移动GPU
if torch.cuda.is_available():
    tensor = tensor.to("cuda")
numpy like operations
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
concat
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
张量乘法

# 矩阵乘法
# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(y1)
torch.matmul(tensor, tensor.T, out=y3)

# 点乘
# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
就地操作

In-place operations Operations that store the result into the
operand are called in-place. They are denoted by a _ suffix. For
example: x.copy_(y), x.t_(), will change x.

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

和numpy的转换

Tensors on the CPU and NumPy arrays can share their underlying memory locations, and changing one will change the other.

改变是共享的

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

Pytorch Tensor
https://dreamerland.cn/2024/07/29/pytorch/Tensor/
作者
Silva31
发布于
2024年7月29日
许可协议