import torch
import numpy as np
# 1>>> 初始化tensor
# (1) 直接创建数值tensor
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
# (2) 由Numpy数组转为tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
# (3) 来自其他tensor
x_rand = torch.rand_like(x_data, dtype=torch.float)
# (4) 创建随机tensor
shape = (2, 3, )
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
# 2>>> tensor属性
tensor1 = torch.rand(3, 4)
print(f"形状:\n {tensor1.shape}")
print(f"数据类型:\n {tensor1.dtype}")
print(f"存放CPU或GPU:\n {tensor1.device}")
print(f"维度:\n {tensor1.ndim}")
print(f"数据:\n {tensor1.data}")
# 3>>> tensor切片
tensor2 = torch.rand(3, 4)
tensor2[..., -1] = 500
print(f"第一行:{tensor2[0]}")
print(f"第一行第一个:{tensor2[0][0]}")
print(f"第一列:{tensor2[:, 0]}")
print(f"最后一列:{tensor2[..., -1]}")
# 4>>> tensor数学运算
# (1) 矩阵相乘,转置
y1 = tensor2 @ tensor2.T
y2 = tensor2.matmul(tensor2.T)
y3 = torch.rand_like(y1)
y4 = torch.matmul(tensor2, tensor2.T, out=y3)
print(y1, "\n", y2, "\n", y3, "\n", y4)
# (2) 逐元素相乘
z1 = tensor2 * tensor2
z2 = tensor2.mul(tensor2)
z3 = torch.rand_like(z1)
z4 = torch.mul(z1, z2, out=z3)
print(z1, "\n", z2, "\n", z3, "\n", z4)
# 5>>> 转为数值
agg = tensor2.sum()
print(agg.item())
# 6>>> tensor加法(直接替换数值)
tensor3 = tensor2.add_(10)
print(tensor2)
print(tensor3)
# 7>>> tensor转为numpy
n = tensor3.numpy()
print(n)
PyTorch Tensor相关操作
最新推荐文章于 2024-09-06 07:22:03 发布
本文详细介绍了如何在PyTorch中使用tensor进行初始化、转换、属性查看、切片、数学运算(如矩阵乘法、逐元素乘法)、求和以及加法操作,并展示了如何将tensor转换回numpy数组。
摘要由CSDN通过智能技术生成