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相关操作
PyTorch中的Tensor操作详解:从创建到数学运算
最新推荐文章于 2025-12-03 12:28:21 发布
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
PyTorch 2.5
PyTorch
Cuda
PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理
880

被折叠的 条评论
为什么被折叠?



