PyTorch基本用法(一)——Numpy,Torch对比
2017-09-18 本文已影响62人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
本文主要是对比Torch与Numpy的一些操作。
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]]
# 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]
# 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]
# 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]
# mean操作
print np.mean(data)
print torch.mean(float_data)
0.0
0.0
# 矩阵相乘
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]