PyTorch Tensor相关操作

本文详细介绍了如何在PyTorch中使用tensor进行初始化、转换、属性查看、切片、数学运算(如矩阵乘法、逐元素乘法)、求和以及加法操作,并展示了如何将tensor转换回numpy数组。
摘要由CSDN通过智能技术生成
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)


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值