『Pytorch』torch基本操作

Tensor基础操作

import torch as t

Tensor基础操作

# 构建张量空间,不初始化
x = t.Tensor(5,3)
x

"""
-2.4365e-20 -1.4335e-03 -2.4290e+25
-1.0283e-13 -2.8296e-07 -2.0769e+22
-1.3816e-33 -6.4672e-32  1.4497e-32
 1.6020e-19  6.2625e+22  4.7428e+30
 4.0095e-08  1.1943e-32 -3.5308e+35
[torch.FloatTensor of size 5x3]
"""

# 构建张量空间,[0,1]均匀分布初始化
x = t.rand(5,3)
x

"""
 0.9618  0.0669  0.1458
 0.3154  0.0680  0.1883
 0.1795  0.4173  0.0395
 0.7673  0.4906  0.6148
 0.0949  0.2366  0.7571
[torch.FloatTensor of size 5x3]
"""

# 查看矩阵形状,返回时tuple的子类,可以直接索引
print(x.shape)
print(x.size())

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

Tensor加法操作

  • 符号加
  • torch.add(out=Tensor)
  • Tensor.add(),方法后面不带有下划线时方法不会修改Tensor本身,仅仅返回新的值
  • Tensor.add_(),方法后面带有下划线时方法会修改Tensor本身,同时返回新的值
Tensor加法操作

# 加法操作:t.add()
y = t.rand(5,3)

print(x + y)
print(t.add(x, y))
result = t.Tensor(5,3)
t.add(x, y, out=result)
print(result)

"""
 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]

 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]

 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]
"""

# 加法操作:Tensor自带方法
print(y)
# 不改变y本身
print("y.add():\n", y.add(x))
print(y)
print("y.add_():\n", y.add_(x))
print(y)

"""
 0.6670  0.3897  0.7832
 0.2788  0.4042  0.5476
 0.2521  0.6759  0.7081
 0.8825  0.8295  0.9462
 0.2325  0.2286  0.7686
[torch.FloatTensor of size 5x3]
"""

y.add():
"""
 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]

 0.6670  0.3897  0.7832
 0.2788  0.4042  0.5476
 0.2521  0.6759  0.7081
 0.8825  0.8295  0.9462
 0.2325  0.2286  0.7686
[torch.FloatTensor of size 5x3]
"""

y.add_():
"""
 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]

 1.6288  0.4566  0.9290
 0.5943  0.4722  0.7359
 0.4316  1.0932  0.7476
 1.6499  1.3201  1.5611
 0.3274  0.4651  1.5257
[torch.FloatTensor of size 5x3]
"""

Tensor索引以及和Numpy.array转换

Tensor对象和numpy的array对象高度相似,不仅可以相互转换,而且:

  1. 转换前后的两者共享内存,所以他们之间的转换很快,而且几乎不会消耗资源,这意味着一个改变另一个也随之改变
  2. 两者在调用时可以相互取代(应该是由于两者的内置方法高度相似)
Tensor索引

# Tensor索引和numpy的array类似

x[:, 1]

"""
 0.0669
 0.0680
 0.4173
 0.4906
 0.2366
[torch.FloatTensor of size 5]
"""

Tensor和numpy转换

a = t.ones_like(x)
b = a.numpy()  # Tensor->array
b

"""
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)
"""

import numpy as np

print(x)

# Tensor和array的交互很强,一定程度上可以相互替代

a = np.ones_like(x)
print(a)

"""
 0.9618  0.0669  0.1458
 0.3154  0.0680  0.1883
 0.1795  0.4173  0.0395
 0.7673  0.4906  0.6148
 0.0949  0.2366  0.7571
[torch.FloatTensor of size 5x3]

[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
"""

b = t.from_numpy(a)  # array->Tensor
print(a)
print(b)
b.add_(1)  # 两者共享内存
print(a)
print(b)

"""
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]

 1  1  1
 1  1  1
 1  1  1
 1  1  1
 1  1  1
[torch.FloatTensor of size 5x3]

[[ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]]

 2  2  2
 2  2  2
 2  2  2
 2  2  2
 2  2  2
[torch.FloatTensor of size 5x3]
"""

最后,实验以下cpu加速,当然,由于我的笔记本没有加速,所以条件是不满足的。

if t.cuda.is_available():
    x = x.cuda()
    y = y.cuda()
    x+y

原文地址:https://www.cnblogs.com/hellcat/p/8438708.html

时间: 2024-07-31 02:21:34

『Pytorch』torch基本操作的相关文章

『PyTorch』第四弹_通过LeNet初识pytorch神经网络_下

『PyTorch』第四弹_通过LeNet初识pytorch神经网络_上 # Author : Hellcat # Time : 2018/2/11 import torch as t import torch.nn as nn import torch.nn.functional as F class LeNet(nn.Module): def __init__(self): super(LeNet,self).__init__() self.conv1 = nn.Conv2d(3, 6, 5)

『PyTorch』第十二弹_nn.Module和nn.functional

大部分nn中的层class都有nn.function对应,其区别是: nn.Module实现的layer是由class Layer(nn.Module)定义的特殊类,会自动提取可学习参数nn.Parameter nn.functional中的函数更像是纯函数,由def function(input)定义. 由于两者性能差异不大,所以具体使用取决于个人喜好.对于激活函数和池化层,由于没有可学习参数,一般使用nn.functional完成,其他的有学习参数的部分则使用类.但是Droupout由于在训

『PyTorch』第十弹_循环神经网络

『cs231n』作业3问题1选讲_通过代码理解RNN&图像标注训练 对于torch中的RNN相关类,有原始和原始Cell之分,其中RNN和RNNCell层的区别在于前者一次能够处理整个序列,而后者一次只处理序列中一个时间点的数据,前者封装更完备更易于使用,后者更具灵活性.实际上RNN层的一种后端实现方式就是调用RNNCell来实现的. 一.nn.RNN import torch as t from torch import nn from torch.autograd import Variab

『PyTorch』第二弹_张量

参考:http://www.jianshu.com/p/5ae644748f21# 几个数学概念: 标量(Scalar)是只有大小,没有方向的量,如1,2,3等 向量(Vector)是有大小和方向的量,其实就是一串数字,如(1,2) 矩阵(Matrix)是好几个向量拍成一排合并而成的一堆数字,如[1,2;3,4] 其实标量,向量,矩阵它们三个也是张量,标量是零维的张量,向量是一维的张量,矩阵是二维的张量,除此之外,张量不仅可以是三维的,还可以是四维的.五维的... 一点小注意: 1.由于torc

『PyTorch』第一弹_Linux系统下的安装记录

官网首页(http://pytorch.org/)是有安装教程的,但是点击之后没有反应,原因不明,所以不得不自己寻找一个安装方法. 安装参考如下: http://blog.csdn.net/amds123/article/details/69396953 由于我的机器使用Anaconda2.7内部嵌套了Anaconda3.6,而我更倾向于使用3.6版本(个人感觉使用3.x是大势所趋,且3.x的确比2.7方便不少),而我的cuda版本是8,所以我根据自己的情况记录一下安装流程: # 激活环境 so

『Pytorch』静动态图构建对比

对比TensorFlow和Pytorch的动静态图构建上的差异 静态图框架设计好了不能够修改,且定义静态图时需要使用新的特殊语法,这也意味着图设定时无法使用if.while.for-loop等结构,而是需要特殊的由框架专门设计的语法,在构建图时,我们需要考虑到所有的情况(即各个if分支图结构必须全部在图中,即使不一定会在每一次运行时使用到),使得静态图异常庞大占用过多显存. 以动态图没有这个顾虑,它兼容python的各种逻辑控制语法,最终创建的图取决于每次运行时的条件分支选择,下面我们对比一下T

『PyTorch』第五弹_深入理解autograd_下:Variable梯度探究

查看非叶节点梯度的两种方法 在反向传播过程中非叶子节点的导数计算完之后即被清空.若想查看这些变量的梯度,有两种方法: 使用autograd.grad函数 使用hook autograd.grad和hook方法都是很强大的工具,更详细的用法参考官方api文档,这里举例说明基础的使用.推荐使用hook方法,但是在实际使用中应尽量避免修改grad的值. 求z对y的导数 x = V(t.ones(3)) w = V(t.rand(3),requires_grad=True) y = w.mul(x) z

『PyTorch』第五弹_深入理解autograd_下:函数扩展&高阶导数

一.封装新的PyTorch函数 继承Function类 forward:输入Variable->中间计算Tensor->输出Variable backward:均使用Variable 线性映射 from torch.autograd import Function class MultiplyAdd(Function): # <----- 类需要继承Function类 @staticmethod # <-----forward和backward都是静态方法 def forward(

『PyTorch』第六弹_最小二乘法的不同实现手段(待续)

PyTorch的Variable import torch as t from torch.autograd import Variable as V import matplotlib.pyplot as plt from IPython import display # 指定随机数种子 t.manual_seed(1000) def get_fake_data(batch_size=8): x = t.rand(batch_size,1)*20 y = x * 2 + 3 + 3*t.ran