浅谈pytorch和Numpy的区别以及相互转换方法
作者:qq_34535410 时间:2022-02-12 03:51:47
如下所示:
# -*- 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]
'''
来源:https://blog.csdn.net/qq_34535410/article/details/79088952
标签:pytorch,Numpy,转换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Python模块化--模块(Modules)和包(Packages)
2023-03-30 01:14:27
PyTorch一小时掌握之迁移学习篇
2021-12-13 12:37:11
![](https://img.aspxhome.com/file/2023/4/117564_0s.png)
Python实现的KMeans聚类算法实例分析
2021-06-28 04:44:49
![](https://img.aspxhome.com/file/2023/4/88974_0s.png)
Python3中对range()逆序的解释
2023-03-26 10:27:59
javascript新闻图片轮换类
2009-01-09 12:57:00
连接无法用于执行此操作。在此上下文中它可能已被关闭或无效
2011-03-15 23:03:00
Python绘制简单散点图的方法
2023-02-22 02:01:07
![](https://img.aspxhome.com/file/2023/8/87768_0s.jpg)
conda与jupyter notebook kernel核环境不一致的问题解决
2021-07-03 15:43:02
![](https://img.aspxhome.com/file/2023/5/127095_0s.png)
Python 文档解析lxml库的使用详解
2022-01-24 10:42:38
JS出现失效的情况总结
2023-08-24 00:44:42
python贪婪匹配以及多行匹配的实例讲解
2021-12-27 20:01:04
python爬虫 基于requests模块发起ajax的get请求实现解析
2022-01-02 05:04:04
![](https://img.aspxhome.com/file/2023/9/69029_0s.png)
pytorch:torch.mm()和torch.matmul()的使用
2022-05-25 21:32:40
Python实现读取txt文件并画三维图简单代码示例
2023-06-11 15:44:18
IE下float产生双倍margin
2007-12-26 12:29:00
![](https://img.aspxhome.com/file/UploadPic/200712/26/20071226123712415s.gif)
用pywin32实现windows模拟鼠标及键盘动作
2023-07-04 21:26:30
Pandas数据分析之pandas数据透视表和交叉表
2021-01-18 05:43:45
![](https://img.aspxhome.com/file/2023/4/130574_0s.png)
HTML标签tbody的用法
2009-11-02 10:11:00
python使用pandas按照行数分割表格
2021-06-25 03:58:51
![](https://img.aspxhome.com/file/2023/5/72045_0s.jpg)
python flask实现分页效果
2022-07-18 06:19:22
![](https://img.aspxhome.com/file/2023/6/103526_0s.png)