forked from vincent-leguen/PhyDNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
constrain_moments.py
162 lines (148 loc) · 4.44 KB
/
constrain_moments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from numpy import *
from numpy.linalg import *
from scipy.special import factorial
from functools import reduce
import torch
import torch.nn as nn
from functools import reduce
__all__ = ['M2K','K2M']
def _apply_axis_left_dot(x, mats):
assert x.dim() == len(mats)+1
sizex = x.size()
k = x.dim()-1
for i in range(k):
x = tensordot(mats[k-i-1], x, dim=[1,k])
x = x.permute([k,]+list(range(k))).contiguous()
x = x.view(sizex)
return x
def _apply_axis_right_dot(x, mats):
assert x.dim() == len(mats)+1
sizex = x.size()
k = x.dim()-1
x = x.permute(list(range(1,k+1))+[0,])
for i in range(k):
x = tensordot(x, mats[i], dim=[0,0])
x = x.contiguous()
x = x.view(sizex)
return x
class _MK(nn.Module):
def __init__(self, shape):
super(_MK, self).__init__()
self._size = torch.Size(shape)
self._dim = len(shape)
M = []
invM = []
assert len(shape) > 0
j = 0
for l in shape:
M.append(zeros((l,l)))
for i in range(l):
M[-1][i] = ((arange(l)-(l-1)//2)**i)/factorial(i)
invM.append(inv(M[-1]))
self.register_buffer('_M'+str(j), torch.from_numpy(M[-1]))
self.register_buffer('_invM'+str(j), torch.from_numpy(invM[-1]))
j += 1
@property
def M(self):
return list(self._buffers['_M'+str(j)] for j in range(self.dim()))
@property
def invM(self):
return list(self._buffers['_invM'+str(j)] for j in range(self.dim()))
def size(self):
return self._size
def dim(self):
return self._dim
def _packdim(self, x):
assert x.dim() >= self.dim()
if x.dim() == self.dim():
x = x[newaxis,:]
x = x.contiguous()
x = x.view([-1,]+list(x.size()[-self.dim():]))
return x
def forward(self):
pass
class M2K(_MK):
"""
convert moment matrix to convolution kernel
Arguments:
shape (tuple of int): kernel shape
Usage:
m2k = M2K([5,5])
m = torch.randn(5,5,dtype=torch.float64)
k = m2k(m)
"""
def __init__(self, shape):
super(M2K, self).__init__(shape)
def forward(self, m):
"""
m (Tensor): torch.size=[...,*self.shape]
"""
sizem = m.size()
m = self._packdim(m)
m = _apply_axis_left_dot(m, self.invM)
m = m.view(sizem)
return m
class K2M(_MK):
"""
convert convolution kernel to moment matrix
Arguments:
shape (tuple of int): kernel shape
Usage:
k2m = K2M([5,5])
k = torch.randn(5,5,dtype=torch.float64)
m = k2m(k)
"""
def __init__(self, shape):
super(K2M, self).__init__(shape)
def forward(self, k):
"""
k (Tensor): torch.size=[...,*self.shape]
"""
sizek = k.size()
k = self._packdim(k)
k = _apply_axis_left_dot(k, self.M)
k = k.view(sizek)
return k
def tensordot(a,b,dim):
"""
tensordot in PyTorch, see numpy.tensordot?
"""
l = lambda x,y:x*y
if isinstance(dim,int):
a = a.contiguous()
b = b.contiguous()
sizea = a.size()
sizeb = b.size()
sizea0 = sizea[:-dim]
sizea1 = sizea[-dim:]
sizeb0 = sizeb[:dim]
sizeb1 = sizeb[dim:]
N = reduce(l, sizea1, 1)
assert reduce(l, sizeb0, 1) == N
else:
adims = dim[0]
bdims = dim[1]
adims = [adims,] if isinstance(adims, int) else adims
bdims = [bdims,] if isinstance(bdims, int) else bdims
adims_ = set(range(a.dim())).difference(set(adims))
adims_ = list(adims_)
adims_.sort()
perma = adims_+adims
bdims_ = set(range(b.dim())).difference(set(bdims))
bdims_ = list(bdims_)
bdims_.sort()
permb = bdims+bdims_
a = a.permute(*perma).contiguous()
b = b.permute(*permb).contiguous()
sizea = a.size()
sizeb = b.size()
sizea0 = sizea[:-len(adims)]
sizea1 = sizea[-len(adims):]
sizeb0 = sizeb[:len(bdims)]
sizeb1 = sizeb[len(bdims):]
N = reduce(l, sizea1, 1)
assert reduce(l, sizeb0, 1) == N
a = a.view([-1,N])
b = b.view([N,-1])
c = a@b
return c.view(sizea0+sizeb1)