File size: 9,453 Bytes
483c6e9 | 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import minimize
R_OUTER = 3.45
ELL_WALL, ELL_FAR = 0.05, 0.60
SN2_WALL, SN2_FAR, NOISE_ZOOM = 1e-7, 3e-3, 6.0
def linear_interp(xn, idx, y, seed=0):
from scipy.interpolate import LinearNDInterpolator, NearestNDInterpolator
lin = LinearNDInterpolator(xn[idx], y)(xn)
nea = NearestNDInterpolator(xn[idx], y)(xn)
return np.where(np.isfinite(lin), lin, nea)
def stationary_gp(xn, idx, y, seed=0, kernel="matern15"):
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel, Matern, WhiteKernel
base = {"rbf": RBF(length_scale=0.3, length_scale_bounds=(1e-2, 3.0)),
"matern15": Matern(length_scale=0.3, length_scale_bounds=(1e-2, 3.0), nu=1.5),
"matern25": Matern(length_scale=0.3, length_scale_bounds=(1e-2, 3.0), nu=2.5)}[kernel]
k = ConstantKernel(1.0, (1e-3, 1e3)) * base + WhiteKernel(noise_level=1e-3, noise_level_bounds=(1e-6, 1e-1))
gp = GaussianProcessRegressor(kernel=k, normalize_y=True, n_restarts_optimizer=6, random_state=seed)
gp.fit(xn[idx], y)
return gp.predict(xn)
def ell_field(x, y):
rho = R_OUTER / np.maximum(np.hypot(x, y), R_OUTER)
return ELL_WALL + (ELL_FAR - ELL_WALL) * (1.0 - rho)
def noise_field(x, y):
rho = np.clip((NOISE_ZOOM - np.hypot(x, y)) / (NOISE_ZOOM - R_OUTER), 0.0, 1.0)
return SN2_FAR * (SN2_WALL / SN2_FAR) ** rho
def _gibbs(A, B, lA, lB):
d2 = (A[:, 0:1] - B[None, :, 0]) ** 2 + (A[:, 1:2] - B[None, :, 1]) ** 2
l2 = lA[:, None] ** 2 + lB[None, :] ** 2
return 2.0 * lA[:, None] * lB[None, :] / l2 * np.exp(-d2 / l2)
def _nll(K, y):
try:
c, low = cho_factor(K, lower=True, check_finite=False)
except np.linalg.LinAlgError:
return 1e25
a = cho_solve((c, low), y, check_finite=False)
return 0.5 * y @ a + np.log(np.diag(c)).sum() + 0.5 * len(y) * np.log(2 * np.pi)
def _posterior_mean(xn, idx, l_all, K, y, sf2, chunk=2000):
c, low = cho_factor(K, lower=True, check_finite=False)
a = cho_solve((c, low), y, check_finite=False)
out = np.empty(len(xn))
for s in range(0, len(xn), chunk):
e = min(s + chunk, len(xn))
out[s:e] = sf2 * _gibbs(xn[s:e], xn[idx], l_all[s:e], l_all[idx]) @ a
return out
def nonstationary_gp(xn, idx, y, x, yc, hetero=False):
l_all = ell_field(x, yc)
K0 = _gibbs(xn[idx], xn[idx], l_all[idx], l_all[idx])
if hetero:
Dn = np.diag(noise_field(x, yc)[idx])
best = min((minimize(lambda t: _nll(np.exp(t[0]) * K0 + Dn, y), np.log([s]), method="L-BFGS-B",
bounds=[(np.log(1e-3), np.log(1e4))]) for s in (1.0, 0.3, 3.0)), key=lambda r: r.fun)
sf2 = float(np.exp(best.x[0]))
return _posterior_mean(xn, idx, l_all, sf2 * K0 + Dn, y, sf2)
eye = np.eye(len(idx))
bounds = [(np.log(1e-3), np.log(1e4)), (np.log(1e-8), np.log(1e-1))]
best = min((minimize(lambda t: _nll(np.exp(t[0]) * K0 + np.exp(t[1]) * eye, y), np.log(s0), method="L-BFGS-B",
bounds=bounds) for s0 in ([1.0, 1e-3], [0.3, 1e-2], [3.0, 1e-4])), key=lambda r: r.fun)
sf2, sn2 = np.exp(best.x)
return _posterior_mean(xn, idx, l_all, sf2 * K0 + sn2 * eye, y, sf2)
def mlp(xn, idx, y, seed=0, width=64, depth=4, epochs=8000, lr=2e-3):
import torch
import torch.nn as nn
torch.manual_seed(seed)
layers = [nn.Linear(2, width), nn.Tanh()]
for _ in range(depth - 1):
layers += [nn.Linear(width, width), nn.Tanh()]
net = nn.Sequential(*layers, nn.Linear(width, 1))
X = torch.tensor(xn.astype(np.float32))
Y = torch.tensor(y.astype(np.float32)).view(-1, 1)
opt = torch.optim.Adam(net.parameters(), lr=lr)
sch = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
for _ in range(epochs):
opt.zero_grad()
loss = ((net(X[idx]) - Y) ** 2).mean()
loss.backward()
opt.step()
sch.step()
with torch.no_grad():
return net(X).numpy().ravel()
def _split(n, seed, frac=0.15):
v = np.random.default_rng(seed + 777).choice(n, int(round(frac * n)), replace=False)
return np.setdiff1d(np.arange(n), v), v
def _r2(a, b):
ss = ((a - a.mean()) ** 2).sum()
return 1 - ((a - b) ** 2).sum() / ss if ss > 0 else -np.inf
def fourier_feature_mlp(xn, idx, y, seed=0, sigmas=(1.0, 3.0, 10.0, 30.0, 100.0)):
import torch
import torch.nn as nn
dev = "cuda" if torch.cuda.is_available() else "cpu"
X = torch.tensor(xn, dtype=torch.float32, device=dev)
def train(sig, tr, ytr, ev, epochs):
g = torch.Generator(device="cpu").manual_seed(seed)
B = (torch.randn(2, 256, generator=g) * sig).to(dev)
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(),
nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 1)).to(dev)
feat = lambda q: torch.cat([torch.sin(2 * np.pi * q @ B), torch.cos(2 * np.pi * q @ B)], 1)
opt = torch.optim.Adam(net.parameters(), lr=2e-3)
sch = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs)
xt, yt = feat(X[tr]), torch.tensor(ytr, dtype=torch.float32, device=dev).view(-1, 1)
for _ in range(epochs):
opt.zero_grad()
loss = ((net(xt) - yt) ** 2).mean()
loss.backward()
opt.step()
sch.step()
with torch.no_grad():
out = torch.cat([net(feat(X[s:s + 8192])) for s in range(0, len(xn), 8192)]).cpu().numpy().ravel()
return out[ev] if ev is not None else out
t, v = _split(len(idx), seed)
scores = [float(_r2(y[v], train(s, idx[t], y[t], idx[v], 3000))) for s in sigmas]
return train(sigmas[int(np.argmax(scores))], idx, y, None, 8000)
def _dip_net(ch=48):
import torch
import torch.nn as nn
def cbr(i, o):
return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.LeakyReLU(0.1),
nn.Conv2d(o, o, 3, padding=1), nn.BatchNorm2d(o), nn.LeakyReLU(0.1))
class Net(nn.Module):
def __init__(self):
super().__init__()
self.e1, self.e2 = cbr(2, ch), cbr(ch, 2 * ch)
self.pool = nn.MaxPool2d(2)
self.up = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
self.d1 = cbr(3 * ch, ch)
self.out = nn.Conv2d(ch, 1, 1)
self.act = nn.Softplus()
def forward(self, z):
e1 = self.e1(z)
e2 = self.e2(self.pool(e1))
return self.act(self.out(self.d1(torch.cat([self.up(e2), e1], 1))))
return Net()
def _rasterize(x, y, vals, idx, zoom, res):
g = np.linspace(-zoom, zoom, res)
GX, GY = np.meshgrid(g, g)
xi, yi, vi = x[idx], y[idx], vals
inwin = (np.abs(xi) <= zoom) & (np.abs(yi) <= zoom)
xi, yi, vi = xi[inwin], yi[inwin], vi[inwin]
col = np.clip(((xi + zoom) / (2 * zoom) * (res - 1)).round().astype(int), 0, res - 1)
row = np.clip(((yi + zoom) / (2 * zoom) * (res - 1)).round().astype(int), 0, res - 1)
obs, cnt = np.zeros((res, res)), np.zeros((res, res))
np.add.at(obs, (row, col), vi)
np.add.at(cnt, (row, col), 1.0)
mask = cnt > 0
obs[mask] /= cnt[mask]
return obs, mask, np.hypot(GX, GY) > R_OUTER, GX, GY
def deep_image_prior(x, yc, idx, y, seed=0, val_seed=0, zoom=16.0, res=256, iters=2500, check=25, lr=0.01, val_frac=0.15):
import torch
from scipy.interpolate import griddata
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
obs, mask, solid, GX, GY = _rasterize(x, yc, y, idx, zoom, res)
rc = np.argwhere(mask)
pick = np.random.default_rng(val_seed).choice(len(rc), max(1, int(val_frac * len(rc))), replace=False)
val = np.zeros_like(mask)
val[rc[pick, 0], rc[pick, 1]] = True
torch.manual_seed(seed)
np.random.seed(seed)
lin = torch.linspace(-1, 1, res)
gy, gx = torch.meshgrid(lin, lin, indexing="ij")
z = torch.stack([gx, gy], 0)[None].to(dev)
z = z + 0.1 * torch.randn_like(z)
Y = torch.tensor(obs, dtype=torch.float32, device=dev)[None, None]
tr_m = torch.tensor(mask & ~val, device=dev)
va_m = torch.tensor(val, device=dev)
so_m = torch.tensor(solid, device=dev)
net = _dip_net().to(dev)
opt = torch.optim.Adam(net.parameters(), lr=lr)
best_val, best = -1e9, None
for it in range(iters):
opt.zero_grad()
loss = ((net(z)[0, 0][tr_m] - Y[0, 0][tr_m]) ** 2).mean()
loss.backward()
opt.step()
if it % check == 0 or it == iters - 1:
with torch.no_grad():
out = net(z)
p, t = out[0, 0][va_m], Y[0, 0][va_m]
st = ((t - t.mean()) ** 2).sum()
vr = float(1 - ((t - p) ** 2).sum() / st) if st > 0 else float("nan")
if vr > best_val:
gbest = out[0, 0].detach().clone()
gbest[~so_m] = 0.0
best_val, best = vr, gbest.cpu().numpy()
win = (np.abs(x) <= zoom) & (np.abs(yc) <= zoom)
pred = np.zeros(len(x))
pred[win] = griddata(np.stack([GX.ravel(), GY.ravel()], 1), best.ravel(),
np.stack([x[win], yc[win]], 1), method="linear", fill_value=0.0)
return pred, best_val
|