- torch和np中transpose的区别
import numpy as np
import torch
from torch.autograd import Variable
a=np.array([[1,2,3],[4,5,6]])
print(a)
# transpose交换tensor中的两个维度,与顺序无关
print(Variable(torch.LongTensor(a)).transpose(0, 1))
print(Variable(torch.LongTensor(a)).transpose(1, 0))
# transpose函数的参数输入是基于维度编号的
print(a.transpose(0,1))
print(a.transpose(1,0))
[[1 2 3]
[4 5 6]]
tensor([[1, 4],
[2, 5],
[3, 6]])
tensor([[1, 4],
[2, 5],
[3, 6]])
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
[[1 4]
[2 5]
[3 6]]
-
numpy与torch之间相互转换
numpy中的ndarray转化成pytorch中的tensor : torch.from_numpy()
a=np.array([[1,1],[1,2]])
b=torch.from_numpy(a)
print(b.type)
b=b.float()
print(b.type)
<bound method _type of
1 1
1 2
[torch.LongTensor of size 2x2]
>
<bound method _type of
1 1
1 2
[torch.FloatTensor of size 2x2]
>
pytorch中的tensor转化成numpy中的ndarray : numpy()
- nn.softmax接受torch.FloatTensor
import numpy as np
import torch
from torch.autograd import Variable
from torch import nn as nn
f=nn.Softmax()
c=torch.Tensor([[1,1],[1,2]])
print(c.type)
print(f(c))
<bound method _type of
1 1
1 2
[torch.FloatTensor of size 2x2]
>
>
Variable containing:
0.5000 0.5000
0.2689 0.7311
[torch.FloatTensor of size 2x2]