点赞收藏关注!
如需转载请注明出处!
张量与数组和矩阵非常相似。
在PyTorch中,使用张量来编码模型的输入和输出,以及模型的参数。
张量可以在GPU或其他硬件加速器上运行。 张量和NumPy数组通常可以共享相同的底层内存,从而消除了复制数据的需要。
对自动微分进行了优化。
import torch
import numpy as np
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
#新张量保留参数张量的属性(形状,数据类型)
x_ones = torch.ones_like(x_data) # 保留x_data的属性
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 重写x_data的数据类型
print(f"Random Tensor: \n {x_rand} \n")
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}")
张量属性描述它们的形状、数据类型和存储它们的设备
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}")
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
t1 = torch.cat([tensor, tensor], dim=1)
print(t1)
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
tt = torch.from_numpy(n)
print(f"t:{tt}")
#计算两个张量之间的矩阵乘法。Y1 y2 y3的值是一样的
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print(f"y1: {y1}")
print(f"y2: {y2}")
print(f"y3: {y3}")
#它计算元素的乘积。z1 z2 z3的值是一样的
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
print(f"z1: {z1}")
print(f"z2: {z2}")
print(f"z3: {z3}")
如有帮助,点赞收藏关注!