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

yipeiwu_com6年前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设计】。

相关文章

Pytorch之Variable的用法

1.简介 torch.autograd.Variable是Autograd的核心类,它封装了Tensor,并整合了反向传播的相关实现 Variable和tensor的区别和联系 Vari...

python中wx将图标显示在右下角的脚本代码

复制代码 代码如下:import wx import imagesclass DemoTaskBarIcon(wx.TaskBarIcon):    TBM...

python通过索引遍历列表的方法

本文实例讲述了python通过索引遍历列表的方法。分享给大家供大家参考。具体如下: python中我们可以通过for循环来遍历列表: colours = ["red","green"...

Python tempfile模块学习笔记(临时文件)

tempfile.TemporaryFile 如何你的应用程序需要一个临时文件来存储数据,但不需要同其他程序共享,那么用TemporaryFile函数创建临时文件是最好的选择。其他的应用...

bpython 功能强大的Python shell

bpython 功能强大的Python shell

Python是一个非常实用、流行的解释型编程语言,其优势之一就是可以借助其交互的shell进行探索式地编程。你可以试着输入一些代码,然后马上获得解释器的反馈,而不必专门写一个脚本。但是P...