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正则分组的应用

复制代码 代码如下:import retext='V101_renow.Android.2.2.Normal.1.Alpha.apk?IMSI=460029353813976&MOBIL...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

在python 不同时区之间的差值与转换方法

之前有个程序,里面有个时间部分是按照国内时区,也就是东八区,来写的,程序中定义了北京时间2点到八点进行检查;后面程序在国外机器上,例如说韩国,欧美等,执行的时候发现会有时间上的问题,因为...

Python中利用sqrt()方法进行平方根计算的教程

 sqrt()方法返回x的平方根(x>0)。 语法 以下是sqrt()方法的语法: import math math.sqrt( x ) 注意:此函数是无法直...

Python docx库用法示例分析

本文实例分析了Python docx库用法。分享给大家供大家参考,具体如下: 打开及保存文件: from docx import Document document = Docume...