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中的线程threading.Thread()使用详解

python中的线程threading.Thread()使用详解

1. 线程的概念: 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈...

Python实现队列的方法

本文实例讲述了Python实现队列的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python queue = [] def enQ():...

numpy.meshgrid()理解(小结)

numpy.meshgrid()理解(小结)

本文的目的是记录meshgrid()的理解过程: step1. 通过一个示例引入创建网格点矩阵; step2. 基于步骤1,说明meshgrid()的作用; step3. 详细解读mes...

Python算法之栈(stack)的实现

本文以实例形式展示了Python算法中栈(stack)的实现,对于学习数据结构域算法有一定的参考借鉴价值。具体内容如下: 1.栈stack通常的操作: Stack() 建立一个空的栈对象...

Python中装饰器学习总结

本文研究的主要内容是Python中装饰器相关学习总结,具体如下。 装饰器(decorator)功能 引入日志 函数执行时间统计 执行函数前预备处理 执行函数后清理功能...