pytorch如何将Variable或Tensor转换为numpy

当我们使用pytorch时候,我们常常需要将Variable转换为numpyTensor转换为numpy;比如我们使用torch.Tensortorch.FloatTensor的时候,我们

一、Tensornumpy之间的相互转化

1、Tensor张量转化为numpy

a = torch.FloatTensor(2,3)
print a.numpy();

2、将numpy转换为Tensor张量

a = np.ones(5)
torch.from_numpy(a)

二、Variablenumpy之间的相互转化

1、Variable张量转化为numpy
其实这里的转换和Tensornumpy之间的相互转化差不多,只是我们的需要先提取出来我们Variable中的数据即可,我们可以使用variable.data来将Variable转为Tensor

import torch
from torch.autograd import Variable

a = Variable(torch.FloatTensor(2,3))
print a.data.numpy()

2、将numpy转换为Variable
其实这个不需要过多的介绍,这个只是把numpy转化为torch并且再将torch转化为Variable

import torch
import numpy as np
from torch.autograd import Variable

a = np.ones(5)
print Variable(torch.from_numpy(a))

转自pytorch中文网

实例

# input numpy array
In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2)

# input tensors in two different ways
In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr)

# their types
In [93]: type(arr), type(t1), type(t2)
Out[93]: (numpy.ndarray, torch.FloatTensor, torch.FloatTensor)

# ndarray 
In [94]: arr
Out[94]: 
array([[ 0.,  1.],
       [ 2.,  3.],
       [ 4.,  5.],
       [ 6.,  7.],
       [ 8.,  9.]], dtype=float32)

我知道PyTorch张量器共享 NumPy ndarrays 的内存缓冲区。因此,改变一个将反映在另一个。所以,在这里我正在切片并更新Tensor中的一些值t2

In [98]: t2[:, 1] = 23.0

正如预期的那样,它已经更新t2,arr因为它们共享相同的内存缓冲区。

In [99]: t2
Out[99]: 

  0  23
  2  23
  4  23
  6  23
  8  23
[torch.FloatTensor of size 5x2]


In [101]: arr
Out[101]: 
array([[  0.,  23.],
       [  2.,  23.],
       [  4.,  23.],
       [  6.,  23.],
       [  8.,  23.]], dtype=float32)

但是,t1也在更新。请记住,t1使用torch.Tensor()while t2构建使用torch.from_numpy()

In [100]: t1
Out[100]: 

  0  23
  2  23
  4  23
  6  23
  8  23
[torch.FloatTensor of size 5x2]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值