In [2]:
import torch
import numpy as np
torch.__version__
Out[2]:
In [3]:
a = torch.arange(1000).view((20, 10, 5))
a.size()
Out[3]:
In [4]:
a[1, 2].size(), a[1, 2, 3].size()
Out[4]:
In [5]:
idx = torch.LongTensor([[0, 2, 3], [0, 2, 4]])
a[idx].size(), a[idx[0]].size()
Out[5]:
In [6]:
a[[0, 0], [0, 0], [0, 1]]
Out[6]:
In [7]:
idx
a[0, 2, 3]
Out[7]:
In [8]:
a[idx[:, 0], idx[:, 1], idx[:, 2]]
Out[8]:
In [9]:
A = np.arange(24).reshape((4, 3, 2))
A[[3, 0, 0, 1], [1, 2, 2, 0], [0, 0, 0, 0]].shape
Out[9]:
In [10]:
A = np.arange(12).reshape((4, 3))
print(A)
A[[2, 0], [0, 1]]
Out[10]:
In [11]:
idx = torch.LongTensor([0, 2, 1])
a[idx].size()
a.size(), a.select(0, 2).size()
Out[11]:
In [12]:
a.index_select(0, idx).size()
Out[12]:
In [13]:
b = torch.tensor([[1, 2], [3, 4], [5, 6]]) + 10
idx2 = torch.LongTensor([[0, 1]])
torch.gather(b, 0, idx2)
Out[13]:
In [14]:
import numpy as np
In [15]:
A = np.arange(10, 16).reshape(3, 2)
A[[1, 0], [1, 0]]
Out[15]:
In [ ]:
In [16]:
x = torch.arange(10, 50, dtype=torch.float).view(4, 10)
xlen = torch.LongTensor([4, 8, 1, 10])
m = torch.arange(x.size(1)).unsqueeze(0).expand(x.size())
mask = xlen.unsqueeze(1).expand(x.size()) <= m
x[mask] = float('-inf')
x
Out[16]:
In [17]:
s = torch.nn.Softmax(dim=-1)
s(x)
Out[17]:
In [18]:
ground_truth = torch.LongTensor(4, 5).random_(0, 3)
ground_truth
Out[18]:
In [19]:
prediction = torch.LongTensor(4, 5).random_(0, 3)
prediction
Out[19]:
In [20]:
doc_lens = torch.LongTensor([2, 5, 4, 1])
In [21]:
m = torch.arange(ground_truth.size(1)).unsqueeze(0).expand(ground_truth.size())
mask = doc_lens.unsqueeze(1).expand(ground_truth.size()) <= m
mask
Out[21]:
In [22]:
correct = torch.eq(ground_truth, prediction)
correct[mask] = 0
correct
Out[22]:
In [23]:
correct.sum().item() / doc_lens.sum().item()
Out[23]:
In [ ]:
In [99]:
X = torch.arange(36).view(3, -1)
splits = torch.LongTensor([3, 10, 4])
mask = torch.arange(12).unsqueeze(0).expand((3, 12)) < splits.unsqueeze(1).expand((3, 12))
X2 = X.clone()
X2[mask] = 0
X, X2
#X[[0, 1, 2], 2:4]
Out[99]:
In [105]:
X3 = torch.zeros_like(X)
i = np.repeat([0, 1, 2], X.size(1) - splits)
import itertools
j = list(itertools.chain(*(range(s.item(), X.size(1)) for s in splits)))
len(i), len(j)
Out[105]:
In [106]:
flipped_mask = mask[:, list(range(X.size(1)-1, -1, -1))]
X3[~flipped_mask] = X[i, j]
X3
Out[106]:
In [102]:
i = np.repeat([0, 1, 2], splits)
j = list(itertools.chain(*(range(s) for s in splits)))
X3[flipped_mask] = X[i, j]
X3
Out[102]:
In [103]:
X[[0, 1, 2], [0, 2, 3]]
Out[103]:
In [ ]: