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

yipeiwu_com6年前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 文件夹遍历和文件查找的实例讲解

实例如下所示: # -*- coding: utf-8 -*- #to find where use the table on xxxxx xxxxxx production en...

python 实现让字典的value 成为列表

如果想让字典的VALUE成为字典,只有最开始让其成为列表,如下面程序中的b >>> b={} >>> b={1:['sdad']} >>...

pyqt5 tablewidget 利用线程动态刷新数据的方法

pyqt5 tablewidget 利用线程动态刷新数据的方法

问题 知道要用线程,所以就先尝试写了一个线程,然后每次都获取数据,然后直接通过这种方法来朝table里面更新数据。 #python代码 table=MainWindow_ui.tab...

python邮件发送smtplib使用详解

本文实例为大家分享了python邮件发送smtplib使用具体代码,供大家参考,具体内容如下 文件形式的邮件 #!/usr/bin/env python3 #coding: utf...

Python2比较当前图片跟图库哪个图片相似的方法示例

本文实例讲述了Python2比较当前图片跟图库哪个图片相似的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- ''' Created on 20...