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

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

相关文章

django admin 后台实现三级联动的示例代码

在刚进公司的时候,要写一个需求,使用django的admin站点管理,实现一个二级联动的功能,因为要用到django自带的页面,因为不是自定义的,不能直接添加js代码。根据我自己的研究简...

Numpy中转置transpose、T和swapaxes的实例讲解

利用Python进行数据分析时,Numpy是最常用的库,经常用来对数组、矩阵等进行转置等,有时候用来做数据的存储。 在numpy中,转置transpose和轴对换是很基本的操作,下面分别...

python+selenium 定位到元素,无法点击的解决方法

报错 selenium.common.exceptions.WebDriverException: Message: Element is not clickable at poin...

python中input()与raw_input()的区别分析

python中input()与raw_input()的区别分析

使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 纯数字输入 当输入为纯数字时 input返回的是数值类型,如int,f...

详解python的四种内置数据结构

对于每种编程语言一般都会规定一些容器来保存某些数据,就像java的集合和数组一样python也同样有这样的结构 而对于python他有四个这样的内置容器来存储数据,他们都是python语...