Pyorch之numpy与torch之间相互转换方式

yipeiwu_com7年前Python基础

numpy中的ndarray转化成pytorch中的tensor : torch.from_numpy()

pytorch中的tensor转化成numpy中的ndarray : numpy()

代码

import numpy as np
import torch
 
np_arr = np.array([1,2,3,4])
tor_arr=torch.from_numpy(np_arr)
tor2numpy=tor_arr.numpy()
print('\nnumpy\n',np_arr,'\ntorch\n',tor_arr,'\nnumpy\n',tor2numpy)

输出

numpy
 [1 2 3 4] 
torch
 tensor([1, 2, 3, 4], dtype=torch.int32) 
numpy
 [1 2 3 4]

以上这篇Pyorch之numpy与torch之间相互转换方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python安装模块的常见问题及解决方法

1、error: command ‘x86_64-linux-gnu-gcc' failed with exit status 解决办法: # Python 3 $ sudo apt...

Flask框架Jinjia模板常用语法总结

Flask框架Jinjia模板常用语法总结

本文实例总结了Flask框架Jinjia模板常用语法。分享给大家供大家参考,具体如下: 1. 变量表示 {{ argv }} 2. 赋值操作 {% set links =...

Python中函数的参数传递与可变长参数介绍

Python中函数的参数传递与可变长参数介绍

1.Python中也有像C++一样的默认缺省函数 复制代码 代码如下: def foo(text,num=0):     print text,num fo...

django的分页器Paginator 从django中导入类

django的分页器Paginator 从django中导入类

先创建表,然后生成批量数据。 在models文件里 from django.db import models # Create your models here. class...

浅谈Pytorch中的torch.gather函数的含义

浅谈Pytorch中的torch.gather函数的含义

pytorch中的gather函数 pytorch比tensorflow更加编程友好,所以准备用pytorch试着做最近要做的一些实验。 立个flag开始学习pytorch,新开一个分类...