PyTorch - Tensor 张量

Tensor

数据类型

  • data :
  • dtype :
  • shape :
  • device : 张量所在设备,GPU / CPU,是加速的关键
  • requires_grad :
  • grad :
  • grad_fn :
  • is_leaf :

创建方式

torch.tensor() : 直接创建

torch.tensor(							# 从data创建tensor
			data,						# data : 可以是list,numpy
			dtype = None,				# 数据类型,默认与data一致
			device = None,				# 所在设备
			requires_grad = False,		# 是否需要梯度
			pin_memory = False			# 是否存于锁页内存
)	

从数据创建

torch.from_numpy(ndarry)			# 从numpy创建tensor

注意 : 从torch.from_numpy(ndarry)创建的tensor与原ndarray共享内存

torch.rand: (0, 1)均匀分布创建

torch.randn: 标准正态分布创建

张量的拼接

torch.cat() : 在已有维度进行拼接

torch.cat(			# 在已有维度进行拼接
		tensors,	# 张量序列
		dim			# 维度
)
import torch

arr = torch.ones((2, 3))

arr_0 = torch.cat([arr, arr], dim=0)
arr_1 = torch.cat([arr, arr], dim=1)

print("arr:{} shape:{}\narr_0:{} shape:{}\narr_1:{} shape:{}".format(arr, arr.shape, arr_0, arr_0.shape, arr_1, arr_1.shape))

运行上述脚本结果:

F:\Anaconda\envs\pytorch_gpu\python.exe "F:/PyTorch Learning/hello pytorch/hello.py"
arr:tensor([[1., 1., 1.],
        [1., 1., 1.]]) shape:torch.Size([2, 3])
arr_0:tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]) shape:torch.Size([4, 3])
arr_1:tensor([[1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1.]]) shape:torch.Size([2, 6])

Process finished with exit code 0

torch.stack() : 新建维度进行拼接

torch.stack(			# 在已有维度进行拼接
		tensors,	# 张量序列
		dim			# 维度
)
import torch

arr = torch.ones((2, 3))

arr_0 = torch.stack([arr, arr], dim=0)
arr_1 = torch.stack([arr, arr], dim=1)

print("arr:{} shape:{}\narr_0:{} shape:{}\narr_1:{} shape:{}".
      format(arr, arr.shape, arr_0, arr_0.shape, arr_1, arr_1.shape))

运行上述脚本结果:

F:\Anaconda\envs\pytorch_gpu\python.exe "F:/PyTorch Learning/hello pytorch/hello.py"
arr:tensor([[1., 1., 1.],
        [1., 1., 1.]]) shape:torch.Size([2, 3])
arr_0:tensor([[[1., 1., 1.],
         [1., 1., 1.]],

        [[1., 1., 1.],
         [1., 1., 1.]]]) shape:torch.Size([2, 2, 3])
arr_1:tensor([[[1., 1., 1.],
         [1., 1., 1.]],

        [[1., 1., 1.],
         [1., 1., 1.]]]) shape:torch.Size([2, 2, 3])

Process finished with exit code 0

张量的切分

torch.chunk() : 按维度dim进行平均切分

torch.chunk(
			tensor,			# 要切分的张量
			chunks, 		# 平均切的份数
			dim				# 切分的维度
)

torch.split() : 按维度dim进行切分

torch.split(
			tensor,			# 要切分的张量
			split,			# int:按数值进行切分,list:按列表值切分
			dim				# 切分的维度
)

张量的索引

torch.index_select() : 按索引返回拼接后新的张量

torch.index_select(
			tensor,
			index,			# index_select(): argument 'index' must be Tensor, not list
			dim
)

torch.masked_select() : 按同形状布尔值Tensor返回一维张量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值