【colab pytorch】张量操作

1、在pytorch中,有以下9种张量类型

2、查看张量的基本信息

tensor=torch.randn(3,4,5)
print(tensor.size())
print(tensor.type())
print(tensor.dim())

torch.Size([3, 4, 5])

torch.FloatTensor

3

3、命名张量

张量命名是一个非常有用的方法,这样可以方便地使用维度的名字来做索引或其他操作,大大提高了可读性、易用性,防止出错。

# 在PyTorch 1.3之前,需要使用注释
# Tensor[N, C, H, W]
images = torch.randn(32, 3, 56, 56)
images.sum(dim=1)
images.select(dim=1, index=0)
# PyTorch 1.3之后
NCHW = [‘N’, ‘C’, ‘H’, ‘W’]
images = torch.randn(32, 3, 56, 56, names=NCHW)
images.sum(‘C‘).size()#按通道相加

torch.Size([32, 32, 32])

不过需要注意:1.4版本中该特性正在处于测试阶段,因此就不要随便的使用了。

#选择第0个通道
images.select(‘C‘,index=0).size()

torch.Size([32, 32, 32])

# 也可以这么设置
tensor = torch.rand(3,4,1,2,names=(‘C‘, ‘N‘, ‘H‘, ‘W‘))
# 使用align_to可以对维度方便地排序
tensor = tensor.align_to(‘N‘, ‘C‘, ‘H‘, ‘W‘)

4、数据类型转换

# 设置默认类型,pytorch中的FloatTensor远远快于DoubleTensor
torch.set_default_tensor_type(torch.FloatTensor)

# 类型转换
tensor = tensor.cuda()
tensor = tensor.cpu()
tensor = tensor.float()
tensor = tensor.long()

5、tensor和numpy.ndarray转换

除了CharTensor,其他所有CPU上的张量都支持转换为numpy格式然后再转换回来。

ndarray = tensor.cpu().numpy()
tensor = torch.from_numpy(ndarray).float()
tensor = torch.from_numpy(ndarray.copy()).float() # If ndarray has negative stride.

6、tensor和PIL.Image转换

pytorch中的张量默认采用[N, C, H, W]的顺序,并且数据范围在[0,1],需要进行转置和规范化

PIL.Image转换为tensor

from PIL import Image
import numpy as np
image=r‘/content/drive/My Drive/colab notebooks/image/test.jpg‘
tensor=torch.from_numpy(np.asarray(Image.open(image))).permute(2,0,1).float()/255.0
tensor.size()

torch.Size([3, 300, 200])

另一种方式:

import torchvision
tensor=torchvision.transforms.functional.to_tensor(PIL.Image.open(path))
tensor.size()

torch.Size([3, 300, 200])

tensor转换为PIL.Image

img=Image.fromarray(torch.clamp(tensor*255,min=0,max=255).byte().permute(1,2,0).cpu().numpy())
print(type(img))

<class ‘PIL.Image.Image‘>

另一种方式:

image = torchvision.transforms.functional.to_pil_image(tensor)

7、np.ndarray和PIL.Image进行转换

np.ndarray转换为PIL.Image

image = PIL.Image.fromarray(ndarray.astype(np.uint8))

PIL.Image转换为np.ndarray

ndarray = np.asarray(PIL.Image.open(path))

8、从只包含一个元素的tensor中取出值

value = torch.rand(1)
print(value)
print(value.item())

tensor([0.2959])

0.2958560585975647

9、改变张量的形状

# 在将卷积层输入全连接层的情况下通常需要对张量做形变处理,
# 相比torch.view,torch.reshape可以自动处理输入张量不连续的情况。
tensor = torch.rand(2,3,4)
shape = (6, 4)
tensor = torch.reshape(tensor, shape)

10、打乱顺序

tensor = tensor[torch.randperm(tensor.size(0))]  # 打乱第一个维度

11、水平翻转

# pytorch不支持tensor[::-1]这样的负步长操作,水平翻转可以通过张量索引实现
# 假设张量的维度为[N, C, H, W].
tensor = tensor[:,:,:,torch.arange(tensor.size(3) - 1, -1, -1).long()]

12、复制张量

# Operation                 |  New/Shared memory | Still in computation graph |
tensor.clone()            # |        New         |          Yes               |
tensor.detach()           # |      Shared        |          No                |
tensor.detach.clone()()   # |        New         |          No                |

13、张量拼接

‘‘‘
注意torch.cat和torch.stack的区别在于torch.cat沿着给定的维度拼接,
而torch.stack会新增一维。例如当参数是3个10x5的张量,torch.cat的结果是30x5的张量,
而torch.stack的结果是3x10x5的张量。
‘‘‘
tensor = torch.cat(list_of_tensors, dim=0)
tensor = torch.stack(list_of_tensors, dim=0)
t1=torch.randn(10,5)
t2=torch.randn(10,5)
t3=torch.randn(10,5)
s1=torch.cat([t1,t2,t3],dim=0)
s2=torch.stack([t1,t2,t3],dim=0)
print(s1.size())
print(s2.size())

torch.Size([30, 5])

torch.Size([3, 10, 5])

14、将整数标签转换为ont-hot码

tensor=torch.tensor([0,2,1,3])
N=tensor.size(0)
num_classes=4
one_hot=torch.zeros(N,num_classes).long()
one_hot.scatter_(dim=1, index=torch.unsqueeze(tensor, dim=1), src=torch.ones(N, num_classes).long())

tensor([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])

15、得到非零元素

torch.nonzero(tensor)               # index of non-zero elements
torch.nonzero(tensor==0)            # index of zero elements
torch.nonzero(tensor).size(0)       # number of non-zero elements
torch.nonzero(tensor == 0).size(0)  # number of zero elements

16、判断两个张量相等

torch.allclose(tensor1, tensor2)  # float tensor
torch.equal(tensor1, tensor2)     # int tensor

17、张量扩展

# Expand tensor of shape 64*512 to shape 64*512*7*7.
tensor = torch.rand(64,512)
torch.reshape(tensor, (64, 512, 1, 1)).expand(64, 512, 7, 7).size()

torch.Size([64, 512, 7, 7])

18、矩阵乘法

# Matrix multiplcation: (m*n) * (n*p) * -> (m*p).
result = torch.mm(tensor1, tensor2)

# Batch matrix multiplication: (b*m*n) * (b*n*p) -> (b*m*p)
result = torch.bmm(tensor1, tensor2)

# Element-wise multiplication.
result = tensor1 * tensor2

19、计算两组数据之间的两两欧式距离

利用广播机制

dist = torch.sqrt(torch.sum((X1[:,None,:] - X2) ** 2, dim=2))

原文地址:https://www.cnblogs.com/xiximayou/p/12430691.html

时间: 2024-08-30 18:34:01

【colab pytorch】张量操作的相关文章

pytorch张量数据索引切片与维度变换操作大全(非常全)

(1-1)pytorch张量数据的索引与切片操作1.对于张量数据的索引操作主要有以下几种方式:a=torch.rand(4,3,28,28):DIM=4的张量数据a(1)a[:2]:取第一个维度的前2个维度数据(不包括2):(2)a[:2,:1,:,:]:取第一个维度的前两个数据,取第2个维度的前1个数据,后两个维度全都取到:(3)a[:2,1:,:,:]:取第一个维度的前两个数据,取第2个维度的第1个索引到最后索引的数据(包含1),后两个维度全都取到:(4)a[:2,-3:]:负号表示第2个维

深度之眼PyTorch训练营第二期 ---2、张量操作与线性回归

一.张量的操作:拼接.切分.索引和变换 1.拼接 (1)torch.cat()  功能:将张量按照维度dim进行拼接(不会扩张) tensors:张量序列 dim:要拼接的维度 (2)torch.stack()  功能:在新创建的维度dim上进行拼接(会扩张张量的维度) tensors:张量序列 dim:要拼接的维度 (3)torch.chunk()  功能:将张量按维度dim进行平均切分     返回值:张量列表 注意:若不能整除,最后一份张量小于其他张量 input:要切分的张量 chunk

PyTorch张量类型转换

1 numpy与CUDA之间的转换 1.tensor张量与numpy相互转换 tensor ----->numpy import torcha=torch.ones([2,5]) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]])# ********************************** b=a.numpy() array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]], dtype=f

Pytorch数学操作

1 """ 数学操作 """ 2 import torch 3 4 # torch.abs(input,out=None)计算输入张量每个元素的绝对值 5 a0 = torch.abs(torch.FloatTensor([-1, -2, 3])) 6 print(a0) 7 8 # torch.acos(input,out=None)计算输入张量每个元素的反余弦函数 9 a1 = torch.randn(4) 10 b1 = torch.aco

『TensorFlow』简单的数学计算&amp;张量操作

tf.pow() tf.sqrt() tf.add() tf.add_n() tf.subtract()        :减法 tf.matmul()         :矩阵乘法 tf.reduce_sum()  :求和 tf.reduce_mean():求均值,直接给源码定义中的注释 For example: ```python # 'x' is [[1., 1.] # [2., 2.]] tf.reduce_mean(x) ==> 1.5 tf.reduce_mean(x, 0) ==>

一线开发者在Reddit上讨论深度学习框架:PyTorch和TensorFlow到底哪个更好?

本文标签:   机器学习 TensorFlow Google深度学习框架 分布式机器学习 PyTorch   近日,Reddit用户 cjmcmurtrie 发了一个主题为「PyTorch vs. TensorFlow」的讨论帖,想要了解这两大流行的框架之间各自有什么优势. 原帖地址:https://redd.it/5w3q74 帖子一楼写道: 我还没有从 Torch7 迁移到 TensorFlow.我玩过 TensorFlow,但我发现 Torch7 更加直观(也许是我玩得不够?).我也尝试了

PyTorch为何如此高效好用?

C/C++中 Python 扩展对象的简介 你可能知道可以借助 C/C++扩展 Python,并开发所谓的「扩展」.PyTorch 的所有繁重工作由 C/C++实现,而不是纯 Python.为了定义 C/C++中一个新的 Python 对象类型,你需要定义如下实例的一个类似结构: // Python object that backs torch.autograd.Variable structTHPVariable{ PyObject_HEAD torch::autograd::Variabl

PyTorch官方中文文档:torch

torch 包 torch 包含了多维张量的数据结构以及基于其上的多种数学操作.另外,它也提供了多种工具,其中一些可以更有效地对张量和任意类型进行序列化. 它有CUDA 的对应实现,可以在NVIDIA GPU上进行张量运算(计算能力>=2.0). http://www.aibbt.com/a/pytorch/ 张量 Tensors torch.is_tensor[source] torch.is_tensor(obj) 如果obj 是一个pytorch张量,则返回True 参数: obj (Ob

[PyTorch入门之60分钟入门闪击战]之神经网络

神经网络 来源于这里. 神经网络可以使用torch.nn包构建. 现在你对autograd已经有了初步的了解,nn依赖于autograd定义模型并区分它们.一个nn.Module包含了层(layers),和一个用来返回output的方法forward(input). 以下面这个区分数字图像的网络为例: 上图是一个简单的前馈网络.它接受输入,一个层接一层地通过几层网络,最后给出输出. 典型的神经网络训练程序如下: 定义具有一些可学习参数(或权重)的神经网络 迭代输入的数据集 通过网络处理输入 计算