首页 > 编程知识 正文

tensor转array,tensorarray

时间:2023-05-05 12:25:14 阅读:144644 作者:14

使用pytorch时,经常需要将变量转换为numpy或Tensor,然后将其转换为numpy; 例如,当我们使用torch.Tensor和torch.FloatTensor时,我们可以

另一方面,Tensor和numpy之间的相互转换1、Tensor张量到numpy的转换

a=torch.float tensor (2,3 ) print a.numpy ); 2、将numpy转换为张量

a=NP.ones(5) torch.from_numpy(a ) a )二、Variable与numpy之间的相互转换1、Variable张量转换numpy

实际上,这里的转换与Tensor和numpy之间的相互转换几乎相同。 但是,我们的需要是先从我们的Variable中提取数据即可,我们可以使用Variable.data将Variable转换为Tensor

importtorchfromtorch.autogradimportvariablea=variable (torch.float tensor ) 2,3 ) (print a.data.numpy ) ) 2,2,是numpy

其实这个不需要怎么介绍。 这只是将numpy转换为torch,并将torch转换为Variable

importtorchimportnumpyasnpfromtorch.autogradimportvariablea=NP.ones (5) printvariable(torch.from_numpy ) (a ) )

3358 www.Sina.com/# inputnumpyarrayin [ 91 ] : arr=NP.arange (10,dtype=float32 ).reshape(5) 5,2 ) input T2=torch.tensor(arr ),torch.from_numpy ) arr ) theirtyppppy type(T2 ) out(93 ) : ) numpy.ndarray,torch 我知道5.]、[ 6.7.]、[ 8.9.]、dtype=float32]pytorch张量共享NumPy ndarrays的内存缓冲区。 因此,改变一个就会反映在另一个上。 所以,在这里我正在切片更新Tensor的一些值t2

in [ 98 ] : t2 [ :1 ]=23.0如您所料,T2已更新。 因为arr共享同一个内存缓冲区。

in [ 99 ] 3360 t2out [ 99 ] :02323423623823 [ torch.floattensorofsize5x2] in [ 101 ] : arr out [ 101 ] 3360 array223 请注意,t1使用torch.tensor (使用while T2构建,torch.from_numpy ) )

in [ 100 ] : t1out [ 100 ] :0232323423623823 [ torch.floattensorofsize5x2 ]

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。