0
点赞
收藏
分享

微信扫一扫

PyTorch 2 ---基础知识

TiaNa_na 2022-04-19 阅读 37
python

1.张量

(1)创建一个张量

from __future__ import print_function
import torch

#随机初始化一个向量
x = torch.rand(4, 3) 
print(x)

#构造一个矩阵全为 0,而且数据类型是 long
x = torch.zeros(4, 3, dtype=torch.long)
print(x)

#直接使用数据,构造一个张量:

x = torch.tensor([5.5, 3]) 
print(x)

#基于已经存在的 tensor,创建一个 tensor :

x = torch.randn_like(x, dtype=torch.float)

(2)返回维度信息

print(x.size())
print(x.shape)

比起numpy ( size返回的是元素总个数,shape返回的是 (m,n) )

这里返回的值相同,都是 torch.Size ([m,n])

(3)索引

注意:索引结果与原数据共享内存,修改索引结果,原数据也会被修改

x = torch.ones(3, 4, dtype=torch.double)
    print(x)
    y = x[0, :]
    y += 1
    print(y)
    print(x[0, :])
    print(x)

返回结果:

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]], dtype=torch.float64)
tensor([2., 2., 2., 2.], dtype=torch.float64)
tensor([2., 2., 2., 2.], dtype=torch.float64)
tensor([[2., 2., 2., 2.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]], dtype=torch.float64)

(4)clone 如果不想修改原数据,就用clone复制一个副本

    x = torch.ones(3, 4, dtype=torch.double)
    y = x.clone()[0, :] + 1
    print(x[0, :])
    print(y)

输出

tensor([1., 1., 1., 1.], dtype=torch.float64)
tensor([2., 2., 2., 2.], dtype=torch.float64)

(5)改变一个张量的大小 torch.view

    x = torch.ones(3, 4, dtype=torch.double)
    y = x.view(12)
    z = x.view(-1, 6)
    print(x.shape)
    print(y.shape)
    print(z.shape)
    print(x.shape)

返回值 (不会修改原数据的维度)

torch.Size([3, 4])
torch.Size([12])
torch.Size([2, 6])
torch.Size([3, 4])

其他见:https://gitee.com/costant9/thorough-pytorch/blob/main/%E7%AC%AC%E4%BA%8C%E7%AB%A0%20PyTorch%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/2.1%20%E5%BC%A0%E9%87%8F.mdicon-default.png?t=M3C8https://gitee.com/costant9/thorough-pytorch/blob/main/%E7%AC%AC%E4%BA%8C%E7%AB%A0%20PyTorch%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/2.1%20%E5%BC%A0%E9%87%8F.md

举报

相关推荐

0 条评论