아비씨飞飞คิดถึง

  • 3

    获得赞
  • 2

    发布的文章
  • 0

    答辩的项目

pytorch的安装及张量基本创建

PyTorch

最后更新 2020-04-28 15:40 阅读 8821

最后更新 2020-04-28 15:40

阅读 8821

PyTorch

1 Pytorch的安装 

1.1 Pytorch的介绍

 Pytorch是一款facebook发布的深度学习框架,由其易用性,友好性,深受广大用户青睐。

1.2 Pytorch的安装

 安装地址介绍:https://pytorch.org/get-started/locally/

import torch 

torch.__version__

2 Pytorch中数据-张量 

2.1 张量Tensor 张量是一个统称,其中包含很多类型:

0阶张量:标量、常数,

1阶张量:向量,

2阶张量:矩阵,

3阶张量

 ... 

N阶张量

2.2 Pytorch中创建张量

 a.从已有的数据中创建张量

b.从列表中创建

torch.tensor([[1., -1.], [1., -1.]])

 tensor([[ 1.0000, -1.0000], [ 1.0000, -1.0000]]) 

c.使用numpy中的数组创建tensor

 torch.tensor(np.array([[1, 2, 3], [4, 5, 6]])) 

tensor([[ 1, 2, 3], [ 4, 5, 6]]) 

d.创建固定张量

 torch.ones([3,4])  

e. 创建3行4列的全为1的tensor 

torch.zeros([3,4]) 

f. 创建3行4列的全为0的tensor

 torch.ones_like(tensor)  torch.zeros_like(tensor) 创建与tensor相同形状和数据类型的值全为1/0的tensor 

g.torch.empty(3,4) 创建3行4列的空的tensor,会用无用数据进行填充(手工填充torch.fill_) 

h.在一定范围内创建序列张量

a. torch.arange(start, end, step)  从start到end以step为步长取值生成序列

 b. torch.linspace(start, end, number_steps) 从start到end之间等差生成number_steps个数字组成序列 

c. torch.logspace(start, end, number_steps, base=10)在start到end之间等比生成number_steps个数字组成序列

i.创建随机张量

a. torch.rand([3,4])  创建3行4列的随机值的tensor,随机值的区间是[0, 1) 

>>> torch.rand(2, 3)

 tensor([[ 0.8237, 0.5781, 0.6879], 

[ 0.3816, 0.7249, 0.0998]]) 

b. torch.randint(low=0,high=10,size=[3,4]) 创建3行4列的随机整数的tensor,随机值的区间是[low, high) 

>>> torch.randint(3, 10, (2, 2)) 

tensor([[4, 5], [6, 7]]) 

c. torch.randn([3,4]) 创建3行4列的随机数的tensor,随机值的分布式均值为0,方差为1 

2.3 Pytorch中tensor的属性

a. 获取tensor中的数据 

tensor.item() 当tensor中只有一个元素时

tensor.numpy() 转化为numpy数组 

b.获取形状:tensor.size()  tensor.shape 

c.获取数据类型 tensor.dtype 

d.获取阶数: tensor.dim()

2.4 tensor的修改 

a.形状改变: 

tensor.view((3,4)) 类似numpy中的reshape 

tensor.t() 或 tensor.transpose(dim0, dim1) 转置 

tensor.permute() 变更tensor的轴(多轴转置) 

tensor.unsqueeze(dim) tensor.squeeze() 填充或者压缩维度 

tensor.squeeze() 默认去掉所有长度是1的维度,也可以填入维度的下标,指定去掉某个维度 

b.类型的指定或修改 创建数据的时候指定类型

 torch.ones([2,3],dtype=torch.float32) 

c.改变已有tensor的类型

a.type(torch.float) 

a.double() 

 a.类型() 

d.tensor的切片

x[:,1] 第二列所有值 

e.切片赋值

x[:,1] = 1 

注意:切片数据内存不连续

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可,转载请附上原文出处链接和本声明。
本文链接地址:https://www.flyai.com/article/art9df0377c91b48f5b4eab3bf5
讨论
500字
表情
发送
删除确认
是否删除该条评论?
取消 删除