pytorch numpy list类型之间的相互转换实例

yipeiwu_com5年前Python基础

如下所示:

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设计】。

相关文章

python编程开发之类型转换convert实例分析

本文实例讲述了python编程开发之类型转换convert。分享给大家供大家参考,具体如下: 在python的开发过程中,难免会遇到类型转换,这里给出常见的类型转换demo:  ...

对命令行模式与python交互模式介绍

命令行模式与python交互模式 1.在命令行模式下,可以执行 python 进入 Python 交互式环境,也可以执 行 python hello.py 运行一个.py 文件。 2.在...

Python 存储字符串时节省空间的方法

从 Python 3 开始,str 类型代表着 Unicode 字符串。取决于编码的类型,一个 Unicode 字符可能会占 4 个字节,这个有些时候有点浪费内存。 出于内存占用以及性能...

python实现移位加密和解密

python实现移位加密和解密

本文实例为大家分享了python实现移位加密和解密的具体代码,供大家参考,具体内容如下 代码很简单,就不多做解释啦。主要思路是将字符串转为Ascii码,将大小写字母分别移位密钥表示的位...

Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子

scapy是python写的一个功能强大的交互式数据包处理程序,可用来发送、嗅探、解析和伪造网络数据包,常常被用到网络攻击和测试中。 这里就直接用python的scapy搞。 这里是ar...