pytorch numpy list类型之间的相互转换实例
更新时间:2019年08月18日 09:28:04 作者:WYXHAHAHA123
今天小编就为大家分享一篇pytorch numpy list类型之间的相互转换实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
如下所示:
import torch
from torch.autograd import Variable
import numpy as np
'''
pytorch中Variable与torch.Tensor类型的相互转换
'''
# 1.torch.Tensor转换成Variablea=torch.randn((5,3))
b=Variable(a)
print('a',a.type(),a.shape)
print('b',type(b),b.shape)
# 2.Variable转换成torch.Tensor
c=b.data#通过 Variable.data 方法相当于将Variable中的torch.tensor 取出来
print('c',c.type(),c.shape)
'''
torch.tensor与numpy之间的相互转换
'''
# 3.torch.tensor转换成numpy
d=c.numpy()
# 4.numpy转换成torch.tensor
e=torch.from_numpy(d)
print('d',type(d))
print('e',type(e))
'''
numpy和list之间的相互转换 注意这种转换只支持one-dimension array
'''
# 5.numpy转换成list
f1=d.tolist()
f2=list(d)
# 6.list转换成numpy
g=np.asarray(f2)
print('f1',type(f1))
print('f2',type(f2))
print('g',type(g))
'''
a torch.FloatTensor torch.Size([5, 3])
b <class 'torch.Tensor'> torch.Size([5, 3])
c torch.FloatTensor torch.Size([5, 3])
d <class 'numpy.ndarray'>
e <class 'torch.Tensor'>
f1 <class 'list'>
f2 <class 'list'>
g <class 'numpy.ndarray'>
'''
以上这篇pytorch numpy list类型之间的相互转换实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python人工智能之路 之PyAudio 实现录音 自动化交互实现问答
关于音频, PyAudio 这个库, 可以实现开启麦克风录音, 可以播放音频文件等等。文章介绍了如何使用Python第三方库PyAudio进行麦克风录音然后自动播放已经合成的语音实现语音交互回答,需要的朋友可以参考下2019-08-08
对python3 Serial 串口助手的接收读取数据方法详解
今天小编就为大家分享一篇对python3 Serial 串口助手的接收读取数据方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-06-06


最新评论