pytorch之 compare with numpy

复制代码
 1 import torch
 2 import numpy as np
 3 
 4 # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations
 5 
 6 # convert numpy to tensor or vise versa
 7 np_data = np.arange(6).reshape((2, 3))
 8 torch_data = torch.from_numpy(np_data)
 9 tensor2array = torch_data.numpy()
10 print(
11     '\nnumpy array:', np_data,          # [[0 1 2], [3 4 5]]
12     '\ntorch tensor:', torch_data,      #  0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
13     '\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
14 )
15 
16 
17 # abs
18 data = [-1, -2, 1, 2]
19 tensor = torch.FloatTensor(data)  # 32-bit floating point
20 print(
21     '\nabs',
22     '\nnumpy: ', np.abs(data),          # [1 2 1 2]
23     '\ntorch: ', torch.abs(tensor)      # [1 2 1 2]
24 )
25 
26 # sin
27 print(
28     '\nsin',
29     '\nnumpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
30     '\ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
31 )
32 
33 # mean
34 print(
35     '\nmean',
36     '\nnumpy: ', np.mean(data),         # 0.0
37     '\ntorch: ', torch.mean(tensor)     # 0.0
38 )
39 
40 # matrix multiplication
41 data = [[1,2], [3,4]]
42 tensor = torch.FloatTensor(data)  # 32-bit floating point
43 # correct method
44 print(
45     '\nmatrix multiplication (matmul)',
46     '\nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
47     '\ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
48 )
49 # incorrect method
50 data = np.array(data)
51 print(
52     '\nmatrix multiplication (dot)',
53     '\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]]
54     '\ntorch: ', tensor.dot(tensor)     # this will convert tensor to [1,2,3,4], you'll get 30.0
55 )
复制代码

 仅为自己练习,没有其他用途

posted @   _Meditation  阅读(280)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示