Pytorch 中 numpy, Tensor and Variable

  1. 关于求梯度,只有我们定义的Variable才会被求梯度,由creator创造的不会去求梯度
  2. 自己定义Variable的时候,记得Variable(Tensor, requires_grad = True),这样才会被求梯度,不然的话,是不会求梯度的
# numpy to Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a) # 如果a 变的话, b也会跟着变,说明b只是保存了一个地址而已,并没有深拷贝
print(b)# Variable只是保存Tensor的地址,如果Tensor变的话,Variable也会跟着变
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
a = np.ones(5)
b = torch.from_numpy(a)# ndarray --> Tensor
a_ = b.numpy() # Tensor --> ndarray
np.add(a, 1, out=a)# 这个和 a = np.add(a,1)有什么区别呢?
# a = np.add(a,1) 只是将a中保存的指针指向新计算好的数据上去
# np.add(a, 1, out=a) 改变了a指向的数据
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
# 将Tensor放到Cuda上
if torch.cuda.is_available():
    x = x.cuda()
    y = y.cuda()
    x + y
  • 1
  • 2
  • 3
  • 4
  • 5
# torch.Tensor(1,2,3) 与 torch.Tensor([1,2,3]) 的区别
torch.Tensor(1,2,3) # 生成一个 shape 为 [1,2,3] 的 tensor
torch.Tensor([1,2,3]) # 生成一个值为 [1,2,3] 的 tensor
  • 1
  • 2
  • 3
# tensor 与 numpy
import torch
from torch.autograd import Variable
import numpy as np
n1 = np.array([1., 2.]).astype(np.float32)
# t1 = torch.FloatTensor(n1)
t1 = torch.from_numpy(n1)
n1[0] = 2.
print(t1)
# 可以看出,当使用 无论是使用 FloatTensor 还是 from_numpy 来创建 tensor
# tensor 只是指向了 初始的值而已,而没有自己再开辟空间。
# FloatTensor(2,3,2) 这个不一样,它是开辟了一个 空间。

神经网络的输入也是Variable类型的,但是并不需要对其求导。

requires_grad控制着是否在反向传播过程中对该节点求梯度:

input = Variable(torch.randn(N, D_in).type(torch.TensorFloat), requires_grad=False)#默认值是False

参考链接:http://blog.csdn.net/u012436149/article/details/54627597 http://blog.csdn.net/victoriaw/article/details/72673110
pytorch如何将Variable或Tensor转换为numpy? https://ptorch.com/news/107.html

猜你喜欢

转载自blog.csdn.net/gaoprincess/article/details/79538540