浅谈pytorch和Numpy的区别以及相互转换方法

yipeiwu_com5年前Python基础

如下所示:

# -*- coding: utf-8 -*-
# @Time  : 2018/1/17 16:37
# @Author : Zhiwei Zhong
# @Site  : 
# @File  : Numpy_Pytorch.py
# @Software: PyCharm

import torch
import numpy as np

np_data = np.arange(6).reshape((2, 3))

# numpy 转为 pytorch格式

torch_data = torch.from_numpy(np_data)
print(
  '\n numpy', np_data,
  '\n torch', torch_data,
)
'''
 numpy [[0 1 2]
 [3 4 5]] 
 torch 
 0 1 2
 3 4 5
[torch.LongTensor of size 2x3]
'''
# torch 转为numpy
tensor2array = torch_data.numpy()
print(tensor2array)
"""
[[0 1 2]
 [3 4 5]]
"""
# 运算符
# abs 、 add 、和numpy类似
data = [[1, 2], [3, 4]]
tensor = torch.FloatTensor(data)    # 转为32位浮点数,torch接受的都是Tensor的形式,所以运算前先转化为Tensor
print(
  '\n numpy', np.matmul(data, data),
  '\n torch', torch.mm(tensor, tensor)    # torch.dot()是点乘
)
'''
 numpy [[ 7 10]
 [15 22]] 
 torch 
 7 10
 15 22
[torch.FloatTensor of size 2x2]
'''

以上这篇浅谈pytorch和Numpy的区别以及相互转换方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python的Twisted框架中使用Deferred对象来管理回调函数

Python的Twisted框架中使用Deferred对象来管理回调函数

首先抛出我们在讨论使用回调编程时的一些观点: 激活errback是非常重要的。由于errback的功能与except块相同,因此用户需要确保它们的存在。他们并不是可选项,而是必选项...

对Python subprocess.Popen子进程管道阻塞详解

问题产生描述 使用子进程处理一个大的日志文件,并对文件进行分析查询,需要等待子进程执行的输出结果,进行下一步处理。 出问题的代码 # 启用子进程执行外部shell命令 def __s...

python time.sleep()是睡眠线程还是进程

python time.sleep()-睡眠线程还是进程? 它会阻止线程。如果查看Python源代码中的Modules / timemodule.c,您会看到在调用中floats...

对Python中创建进程的两种方式以及进程池详解

在Python中创建进程有两种方式,第一种是: from multiprocessing import Process import time def test(): whil...

python线程锁(thread)学习示例

复制代码 代码如下:# encoding: UTF-8import threadimport time# 一个用于在线程中执行的函数def func():  &nbs...