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装饰器使用你可能不知道的几种姿势

前言 在Python中,装饰器是一种十分强大并且好用的语法,一些重复的代码使用装饰器语法的话能够使代码更容易理解及阅读。 因此在这里简单总结了一下Python中装饰器的几种用法以及需要...

python3 常见解密加密算法实例分析【base64、MD5等】

本文实例讲述了python3 常见解密加密算法。分享给大家供大家参考,具体如下: 一.使用base64 Base64编码,64指A-Z、a-z、0-9、+和/这64个字符,还有“=”号不...

Python多继承顺序实例分析

本文实例讲述了Python多继承顺序。分享给大家供大家参考,具体如下: 示例1: #-*- coding:utf-8 -*- #!python2 class A(object):...

python多线程分块读取文件

本文实例为大家分享了python多线程分块读取文件的具体代码,供大家参考,具体内容如下 # _*_coding:utf-8_*_ import time, threading, C...

python DataFrame获取行数、列数、索引及第几行第几列的值方法

1、df=DataFrame([{‘A':'11','B':'12'},{‘A':'111','B':'121'},{‘A':'1111','B':'1211'}]) print d...