浅谈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设计】。

相关文章

编写自定义的Django模板加载器的简单示例

Djangos 内置的模板加载器(在先前的模板加载内幕章节有叙述)通常会满足你的所有的模板加载需求,但是如果你有特殊的加载需求的话,编写自己的模板加载器也会相当简单。 比如:你可以从数据...

Python转换时间的图文方法

Python转换时间的图文方法

time模块常用的中时间的转换。 python中的时间戳:通俗讲就是某个时刻的时间,单位是秒; 获取当前时间的时间戳: time.time() 1)没有参数, 2)返回从1970年1月1...

python算法表示概念扫盲教程

python算法表示概念扫盲教程

本文为大家讲解了python算法表示概念,供大家参考,具体内容如下 常数阶O(1) 常数又称定数,是指一个数值不变的常量,与之相反的是变量 为什么下面算法的时间复杂度不是O(3),而是O...

Python 迭代器工具包【推荐】

  原文:https://git.io/pytips   0x01 介绍了迭代器的概念,即定义了 __iter__() 和 __next__() 方法的对象,或者通过 yield 简化定...

python中format()函数的简单使用教程

python中format()函数的简单使用教程

先给大家介绍下python中format函数,在文章下面给大家介绍python.format()函数的简单使用 ---恢复内容开始--- python中format函数用于字符串的格式化...