从零开始学Pytorch之数据操作
import torchtorch.manual_seed(0)
torch.cuda.manual_seed(0)
print(torch.__version__)
输出pytorch的版本号
创建Tensor
创建一个5x3的未初始化的Tensor
:
x = torch.empty(5, 3)
print(x)
输出为:tensor([[0.0000e+00, 1.0842e-19, 1.6162e+22],[2.8643e-42, 5.6052e-45, 0.0000e+00],[0.0000e+00, 0.0000e+00, 0.0000e+00],[0.0000e+00, 0.0000e+00, 0.0000e+00],[0.0000e+00, 1.0842e-19, 1.3314e+22]])
创建一个5x3的随机初始化的Tensor
:
x = torch.rand(5, 3)
print(x)
输出为:
tensor([[0.4963, 0.7682, 0.0885],[0.1320, 0.3074, 0.6341],[0.4901, 0.8964, 0.4556],[0.6323, 0.3489, 0.4017],[0.0223, 0.1689, 0.2939]])
创建一个5x3的long型全0的Tensor
:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
输出为:
tensor([[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0],[0, 0, 0]])
直接根据数据创建:
x = torch.tensor([5.5, 3])
print(x)
输出为:
tensor([5.5000, 3.0000])
还可以通过现有的Tensor
来创建,此方法会默认重用输入Tensor
的一些属性,例如数据类型,除非自定义数据类型。
x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x) 输出为:
tensor([[1., 1., 1.],[1., 1., 1.],[1., 1., 1.],[1., 1., 1.],[1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.6035, 0.8110, -0.0451],[ 0.8797, 1.0482, -0.0445],[-0.7229, 2.8663, -0.5655],[ 0.1604, -0.0254, 1.0739],[ 2.2628, -0.9175, -0.2251]])
我们可以通过shape
或者size()
来获取Tensor
的形状:
print(x.size())
print(x.shape)
输出为:
torch.Size([5, 3])
torch.Size([5, 3])
注意:返回的torch.Size其实就是一个tuple, 支持所有tuple的操作。
操作
算术操作
- 加法形式一
y = torch.rand(5, 3)
print(x + y)
输出为:
tensor([[ 1.3967, 1.0892, 0.4369],[ 1.6995, 2.0453, 0.6539],[-0.1553, 3.7016, -0.3599],[ 0.7536, 0.0870, 1.2274],[ 2.5046, -0.1913, 0.4760]])
- 加法形式二
print(torch.add(x, y))
输出为:
tensor([[ 1.3967, 1.0892, 0.4369],[ 1.6995, 2.0453, 0.6539],[-0.1553, 3.7016, -0.3599],[ 0.7536, 0.0870, 1.2274],[ 2.5046, -0.1913, 0.4760]])
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
输出为:
tensor([[ 1.3967, 1.0892, 0.4369],[ 1.6995, 2.0453, 0.6539],[-0.1553, 3.7016, -0.3599],[ 0.7536, 0.0870, 1.2274],[ 2.5046, -0.1913, 0.4760]])
- 加法形式三、inplace
# adds x to y
y.add_(x)
print(y)
输出为:
tensor([[ 1.3967, 1.0892, 0.4369],[ 1.6995, 2.0453, 0.6539],[-0.1553, 3.7016, -0.3599],[ 0.7536, 0.0870, 1.2274],[ 2.5046, -0.1913, 0.4760]])
注:PyTorch操作inplace版本都有后缀"_", 例如
x.copy_(y), x.t_()
索引
我们还可以使用类似NumPy的索引操作来访问Tensor
的一部分,需要注意的是:索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。
y = x[0, :]
y += 1
print(y)
print(x[0, :]) # 源tensor也被改了输出为:
tensor([1.6035, 1.8110, 0.9549])
tensor([1.6035, 1.8110, 0.9549])
改变形状
用view()
来改变Tensor
的形状:
y = x.view(15)
z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())
输出为:
torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])
注意view()
返回的新tensor与源tensor共享内存,也即更改其中的一个,另外一个也会跟着改变。
x += 1
print(x)
print(y) # 也加了1
输出为:
tensor([[2.6035, 2.8110, 1.9549],[1.8797, 2.0482, 0.9555],[0.2771, 3.8663, 0.4345],[1.1604, 0.9746, 2.0739],[3.2628, 0.0825, 0.7749]])
tensor([2.6035, 2.8110, 1.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])
如果不想共享内存,推荐先用clone
创造一个副本然后再使用view
。
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
输出为:
tensor([[ 1.6035, 1.8110, 0.9549],[ 0.8797, 1.0482, -0.0445],[-0.7229, 2.8663, -0.5655],[ 0.1604, -0.0254, 1.0739],[ 2.2628, -0.9175, -0.2251]])
tensor([2.6035, 2.8110, 1.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])
另外一个常用的函数就是item()
, 它可以将一个标量Tensor
转换成一个Python number:
x = torch.randn(1)
print(x)
print(x.item())
输出为:
tensor([2.3466])
2.3466382026672363
广播机制
x = torch.arange(1, 3).view(1, 2)
print(x)
y = torch.arange(1, 4).view(3, 1)
print(y)
print(x + y)
输出为:
tensor([[1, 2]])
tensor([[1],[2],[3]])
tensor([[2, 3],[3, 4],[4, 5]])
Tensor
和NumPy相互转换
numpy()
和from_numpy()
这两个函数产生的Tensor
和NumPy array实际是使用的相同的内存,改变其中一个时另一个也会改变!!!
Tensor
转NumPy
a = torch.ones(5)
b = a.numpy()
print(a, b)a += 1
print(a, b)
b += 1
print(a, b)
输出为:
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]
NumPy数组转Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)a += 1
print(a, b)
b += 1
print(a, b)
输出为;
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)
直接用torch.tensor()
将NumPy数组转换成Tensor
,该方法总是会进行数据拷贝,返回的Tensor
和原来的数据不再共享内存。
# 用torch.tensor()转换时不会共享内存
c = torch.tensor(a)
a += 1
print(a, c)
输出为:
[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)
Tensor
on GPU
# 以下代码只有在PyTorch GPU版本上才会执行
if torch.cuda.is_available():device = torch.device("cuda") # GPUy = torch.ones_like(x, device=device) # 直接创建一个在GPU上的Tensorx = x.to(device) # 等价于 .to("cuda")z = x + yprint(z)print(z.to("cpu", torch.double)) # to()还可以同时更改数据类型
从零开始学Pytorch之数据操作相关推荐
- 从零开始学Pytorch(零)之安装Pytorch
本文首发于公众号"计算机视觉cv" Pytorch优势 聊聊为什么使用Pytorch,个人觉得Pytorch比Tensorflow对新手更为友善,而且现在Pytorch在学术界 ...
- 从零开始学Pytorch(第5天)
从零开始学Pytorch(第5天) 前言 一.模块类的构建 1. nn.Module 2.构建一个线性回归类 二.计算图和自动求导机制 1.计算图 2.自动求导 总结 前言 今天主要了解和学习Pyto ...
- [PyTorch笔记]数据操作
[动手学深度学习PyTorch笔记]--数据操作 1 引言 2 预备知识 2.1 数据操作 2.1.1 入门 2.1.2 运算符 2.1.3 广播机制 2.1.4 索引和切片 2.1.5 节省内存 2 ...
- 从零开始学python大数据与量化交易下载_GitHub - mignonwong/Python-100-Days-1: Python - 100天从新手到大师...
Python - 100天从新手到大师 作者:骆昊 说明:从项目上线到获得8w+星标以来,一直收到反馈说基础部分(前15天的内容)对新手来说是比较困难的,建议有配套视频进行讲解.最近把基础部分的内容重 ...
- 从零开始学python大数据与量化交易下载_GitHub - zhaojie1126/Python-100-Days-1: Python - 100天从新手到大师...
Python - 100天从新手到大师 作者:骆昊 说明:从项目上线到获得8w+星标以来,一直收到反馈说基础部分(前15天的内容)对新手来说是比较困难的,建议有配套视频进行讲解.最近把基础部分的内容重 ...
- 从零开始学python大数据与量化交易下载_GitHub - Lid23/Python-100-Days: Python - 100天从新手到大师...
Python - 100天从新手到大师 作者:骆昊 说明:从项目上线到获得8w+星标以来,一直收到反馈说基础部分(前15天的内容)对新手来说是比较困难的,建议有配套视频进行讲解.最近把基础部分的内容重 ...
- 从零开始学Pytorch(十五)之数据增强
图像增广 在深度卷积神经网络里我们提到过,大规模数据集是成功应用深度神经网络的前提.图像增广(image augmentation)技术通过对训练图像做一系列随机改变,来产生相似但又不同的训练样本,从 ...
- mpandroidchart y轴从0开始_从零开始学Pytorch(十七)之目标检测基础
目标检测和边界框 %matplotlib inline from PIL import Imageimport sys sys.path.append('/home/input/') #数据集路径 i ...
- 从零开始学Pytorch(十七)之目标检测基础
目标检测和边界框 %matplotlib inline from PIL import Imageimport sys sys.path.append('/home/input/') #数据集路径 i ...
最新文章
- 到底选择PostgreSOL还是MySQL?看这里!
- 【Linux 内核 内存管理】虚拟地址空间布局架构 ② ( 用户虚拟地址空间组成 | 内存描述符 mm_struct 结构体源码 )
- DFiddler:A HTTP Packets Listener一个简易版的手机端的Fiddler。
- python辗转相除法求最大公约数的递归函数_Python基于辗转相除法求解最大公约数的方法示例...
- spring配置druid连接池和监控数据库访问性能
- kafka清理数据日志
- Magento: 获取类别所有子类别 (无限级别-目录树) Get All Sub Categories
- 数据安全,配置先行;如何检查,SQL 评估 API
- centos7 mysql.h_centos7下致命错误:mysql/mysql.h:没有那个文件或目录
- Vue之webpack之Babel
- kangle 3.4.8 发布,国产开源 Web 服务器
- Septentrio板卡接收机连接方式
- Python开发基础----数据类型----[列表]
- VSCode 菜单栏不见了,该怎么办
- “囍”博物馆与Interesting 有点意思
- inherits在java中是什么属性_在Java中,要想让一个类继承另一个类,可以使用哪个关键字?()...
- 自助破解winrar
- 理性看待 数据分析师 Hot!
- laravel获取最后一条
- 文本对比。文本编辑距离算法