Tensor
Tenosr是一种和numpy的ndarrays是相同的概念,不同的时tensor可以用GPU来加速
#import sys
#sys.executable
#print(sys.path)
from __future__ import print_function
import torch
x = torch.Tensor(5, 3)
print(x)
1.00000e-31 *
-5.0975 0.0000 -5.0975
0.0000 0.0000 0.0000
0.0000 0.0000 0.0000
0.0000 0.0000 0.0000
0.0000 0.0000 0.0000
[torch.FloatTensor of size 5x3]
x = torch.rand(5, 3)
print(x)
print(x.size())
0.3834 0.8875 0.3252
0.9993 0.6884 0.9710
0.3140 0.4587 0.9075
0.0496 0.9154 0.4637
0.6238 0.2553 0.4406
[torch.FloatTensor of size 5x3]
torch.Size([5, 3])
y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))
0.4426 1.2303 0.8045
1.1960 1.1696 1.3620
0.4249 0.5298 1.0216
0.0576 1.3974 0.7120
0.7984 0.5635 0.7325
[torch.FloatTensor of size 5x3]
0.4426 1.2303 0.8045
1.1960 1.1696 1.3620
0.4249 0.5298 1.0216
0.0576 1.3974 0.7120
0.7984 0.5635 0.7325
[torch.FloatTensor of size 5x3]
result = torch.Tensor(5, 3)
torch.add(x, y, out = result)
print(result)
0.4426 1.2303 0.8045
1.1960 1.1696 1.3620
0.4249 0.5298 1.0216
0.0576 1.3974 0.7120
0.7984 0.5635 0.7325
[torch.FloatTensor of size 5x3]
如果想通过一个操作改变tensor的内容可以用带下滑线的操作,如x.copy(y), x.t(),将会改变x的操作
y.add_(x)
print(y)
0.4426 1.2303 0.8045
1.1960 1.1696 1.3620
0.4249 0.5298 1.0216
0.0576 1.3974 0.7120
0.7984 0.5635 0.7325
[torch.FloatTensor of size 5x3]
torch变量与numpy可以方便的链接起来
a = torch.ones(5)
print(a)
1
1
1
1
1
[torch.FloatTensor of size 5]
b = a.numpy()
print(b)
[ 1. 1. 1. 1. 1.]
将numpy变量转为tensor变量
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out = a)
print(a)
print(b)
[ 2. 2. 2. 2. 2.]
2
2
2
2
2
[torch.DoubleTensor of size 5]