PyTorch基本用法(一)——Numpy,Torch对比

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是对比Torch与Numpy的一些操作。

1
2
3
4
5
6
7
8
9
10
11
import torch
import numpy as np

# numpy的array与torch的tensor的转换
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()

print 'numpy data: ', np_data
print 'torch data: ', torch_data
print 'tensor2array: ', tensor2array
numpy data:  [[0 1 2]
 [3 4 5]]
torch data:  
 0  1  2
 3  4  5
[torch.LongTensor of size 2x3]

tensor2array:  [[0 1 2]
 [3 4 5]]
1
2
3
4
# Tensor的文档:http://pytorch.org/docs/master/tensors.html
data = [-2, -1, 0, 1, 2]
float_data = torch.FloatTensor(data)
print float_data
-2
-1
 0
 1
 2
[torch.FloatTensor of size 5]
1
2
3
# abs操作
print np.abs(data)
print torch.abs(float_data)
[2 1 0 1 2]

 2
 1
 0
 1
 2
[torch.FloatTensor of size 5]
1
2
3
# sin操作
print np.sin(data)
print torch.sin(float_data)
[-0.90929743 -0.84147098  0.          0.84147098  0.90929743]

-0.9093
-0.8415
 0.0000
 0.8415
 0.9093
[torch.FloatTensor of size 5]
1
2
3
# mean操作
print np.mean(data)
print torch.mean(float_data)
0.0
0.0
1
2
3
4
5
6
7
8
9
# 矩阵相乘
data = [[1, 2], [3, 4]]
tensor = torch.FloatTensor(data)

print np.matmul(data, data)
# torch.mm不支持广播形式
print torch.mm(tensor, tensor)
# torch.matmul支持广播形式
print torch.matmul(tensor, tensor)
[[ 7 10]
 [15 22]]

  7  10
 15  22
[torch.FloatTensor of size 2x2]


  7  10
 15  22
[torch.FloatTensor of size 2x2]

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!