|
a |
|
b/experiments/simulations/one_dimensional_prediction.py |
|
|
1 |
import torch |
|
|
2 |
import numpy as np |
|
|
3 |
import matplotlib.pyplot as plt |
|
|
4 |
import pandas as pd |
|
|
5 |
|
|
|
6 |
import seaborn as sns |
|
|
7 |
import sys |
|
|
8 |
|
|
|
9 |
sys.path.append("../..") |
|
|
10 |
from models.gpsa_vi_lmc import VariationalWarpGP |
|
|
11 |
from data.simulated.generate_oned_data import ( |
|
|
12 |
generate_oned_data_affine_warp, |
|
|
13 |
generate_oned_data_gp_warp, |
|
|
14 |
) |
|
|
15 |
from plotting.callbacks import callback_oned |
|
|
16 |
|
|
|
17 |
from sklearn.gaussian_process import GaussianProcessRegressor |
|
|
18 |
from sklearn.gaussian_process.kernels import WhiteKernel, RBF |
|
|
19 |
|
|
|
20 |
import matplotlib |
|
|
21 |
|
|
|
22 |
LATEX_FONTSIZE = 30 |
|
|
23 |
|
|
|
24 |
font = {"size": LATEX_FONTSIZE} |
|
|
25 |
matplotlib.rc("font", **font) |
|
|
26 |
matplotlib.rcParams["text.usetex"] = True |
|
|
27 |
|
|
|
28 |
|
|
|
29 |
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
30 |
|
|
|
31 |
|
|
|
32 |
n_spatial_dims = 1 |
|
|
33 |
n_views = 2 |
|
|
34 |
n_outputs = 10 |
|
|
35 |
n_samples_per_view = 100 |
|
|
36 |
m_G = 20 |
|
|
37 |
m_X_per_view = 20 |
|
|
38 |
|
|
|
39 |
N_EPOCHS = 2000 |
|
|
40 |
PRINT_EVERY = 100 |
|
|
41 |
N_LATENT_GPS = {"expression": 3} |
|
|
42 |
NOISE_VARIANCE = 0.1 |
|
|
43 |
|
|
|
44 |
N_REPEATS = 2 |
|
|
45 |
|
|
|
46 |
errors_union, errors_separate, errors_gpsa = [], [], [] |
|
|
47 |
|
|
|
48 |
for repeat_idx in range(N_REPEATS): |
|
|
49 |
|
|
|
50 |
# X, Y, n_samples_list, view_idx = generate_oned_data_affine_warp( |
|
|
51 |
# n_views, |
|
|
52 |
# n_outputs, |
|
|
53 |
# n_samples_per_view, |
|
|
54 |
# noise_variance=NOISE_VARIANCE, |
|
|
55 |
# n_latent_gps=N_LATENT_GPS, |
|
|
56 |
# scale_factor=1., |
|
|
57 |
# additive_factor=1.0, |
|
|
58 |
# ) |
|
|
59 |
X, Y, n_samples_list, view_idx = generate_oned_data_gp_warp( |
|
|
60 |
n_views, |
|
|
61 |
n_outputs, |
|
|
62 |
n_samples_per_view, |
|
|
63 |
noise_variance=NOISE_VARIANCE, |
|
|
64 |
n_latent_gps=N_LATENT_GPS["expression"], |
|
|
65 |
kernel_variance=0.25, |
|
|
66 |
kernel_lengthscale=5.0, |
|
|
67 |
) |
|
|
68 |
|
|
|
69 |
## Drop part of the second view (this is the part we'll try to predict) |
|
|
70 |
second_view_idx = view_idx[1] |
|
|
71 |
n_drop = int(1.0 * n_samples_per_view // 2.0) |
|
|
72 |
test_idx = np.random.choice(second_view_idx, size=n_drop, replace=False) |
|
|
73 |
keep_idx = np.setdiff1d(second_view_idx, test_idx) |
|
|
74 |
|
|
|
75 |
train_idx = np.concatenate([np.arange(n_samples_per_view), keep_idx]) |
|
|
76 |
|
|
|
77 |
X_train = X[train_idx] |
|
|
78 |
Y_train = Y[train_idx] |
|
|
79 |
n_samples_list_train = n_samples_list |
|
|
80 |
n_samples_list_train[1] -= n_drop |
|
|
81 |
|
|
|
82 |
n_samples_list_test = [[0], [n_drop]] |
|
|
83 |
|
|
|
84 |
X_test = X[test_idx] |
|
|
85 |
Y_test = Y[test_idx] |
|
|
86 |
|
|
|
87 |
x_train = torch.from_numpy(X_train).float().clone() |
|
|
88 |
y_train = torch.from_numpy(Y_train).float().clone() |
|
|
89 |
x_test = torch.from_numpy(X_test).float().clone() |
|
|
90 |
y_test = torch.from_numpy(Y_test).float().clone() |
|
|
91 |
|
|
|
92 |
data_dict_train = { |
|
|
93 |
"expression": { |
|
|
94 |
"spatial_coords": x_train, |
|
|
95 |
"outputs": y_train, |
|
|
96 |
"n_samples_list": n_samples_list_train, |
|
|
97 |
} |
|
|
98 |
} |
|
|
99 |
|
|
|
100 |
data_dict_test = { |
|
|
101 |
"expression": { |
|
|
102 |
"spatial_coords": x_test, |
|
|
103 |
"outputs": y_test, |
|
|
104 |
"n_samples_list": n_samples_list_test, |
|
|
105 |
} |
|
|
106 |
} |
|
|
107 |
|
|
|
108 |
model = VariationalWarpGP( |
|
|
109 |
data_dict_train, |
|
|
110 |
n_spatial_dims=n_spatial_dims, |
|
|
111 |
m_X_per_view=m_X_per_view, |
|
|
112 |
m_G=m_G, |
|
|
113 |
data_init=False, |
|
|
114 |
minmax_init=False, |
|
|
115 |
grid_init=True, |
|
|
116 |
n_latent_gps=N_LATENT_GPS, |
|
|
117 |
mean_function="identity_fixed", |
|
|
118 |
# fixed_kernel_variances=np.ones(n_views) * 2, |
|
|
119 |
# fixed_kernel_lengthscales=np.ones(n_views) * 2, |
|
|
120 |
# mean_function="identity_initialized", |
|
|
121 |
# fixed_view_idx=0, |
|
|
122 |
).to(device) |
|
|
123 |
|
|
|
124 |
view_idx_train, Ns_train, _, _ = model.create_view_idx_dict(data_dict_train) |
|
|
125 |
view_idx_test, Ns_test, _, _ = model.create_view_idx_dict(data_dict_test) |
|
|
126 |
|
|
|
127 |
## Make predictions for naive alignment |
|
|
128 |
gpr_union = GaussianProcessRegressor(kernel=RBF() + WhiteKernel()) |
|
|
129 |
gpr_union.fit(X=X_train, y=Y_train) |
|
|
130 |
preds = gpr_union.predict(X_test) |
|
|
131 |
error_union = np.mean((preds - Y_test) ** 2) |
|
|
132 |
errors_union.append(error_union) |
|
|
133 |
print("MSE, union: {}".format(round(error_union, 5))) |
|
|
134 |
|
|
|
135 |
## Make predictons for each view separately |
|
|
136 |
preds, truth = [], [] |
|
|
137 |
|
|
|
138 |
for vv in range(n_views): |
|
|
139 |
gpr_separate = GaussianProcessRegressor(kernel=RBF() + WhiteKernel()) |
|
|
140 |
curr_trainX = X_train[view_idx_train["expression"][vv]] |
|
|
141 |
curr_trainY = Y_train[view_idx_train["expression"][vv]] |
|
|
142 |
curr_testX = X_test[view_idx_test["expression"][vv]] |
|
|
143 |
curr_testY = Y_test[view_idx_test["expression"][vv]] |
|
|
144 |
if len(curr_testX) == 0: |
|
|
145 |
continue |
|
|
146 |
gpr_separate.fit(X=curr_trainX, y=curr_trainY) |
|
|
147 |
curr_preds = gpr_separate.predict(curr_testX) |
|
|
148 |
preds.append(curr_preds) |
|
|
149 |
truth.append(curr_testY) |
|
|
150 |
|
|
|
151 |
preds = np.concatenate(preds, axis=0) |
|
|
152 |
truth = np.concatenate(truth, axis=0) |
|
|
153 |
error_separate = np.mean((preds - truth) ** 2) |
|
|
154 |
errors_separate.append(error_separate) |
|
|
155 |
print("MSE, separate: {}".format(round(error_separate, 5))) |
|
|
156 |
# preds = gpr_union.predict(X_test) |
|
|
157 |
|
|
|
158 |
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) |
|
|
159 |
|
|
|
160 |
def train(model, loss_fn, optimizer): |
|
|
161 |
model.train() |
|
|
162 |
|
|
|
163 |
# Forward pass |
|
|
164 |
G_means, G_samples, F_latent_samples, F_samples = model.forward( |
|
|
165 |
X_spatial={"expression": x_train}, view_idx=view_idx_train, Ns=Ns_train |
|
|
166 |
) |
|
|
167 |
|
|
|
168 |
# Compute loss |
|
|
169 |
loss = loss_fn(data_dict_train, F_samples) |
|
|
170 |
|
|
|
171 |
# Compute gradients and take optimizer step |
|
|
172 |
optimizer.zero_grad() |
|
|
173 |
loss.backward() |
|
|
174 |
optimizer.step() |
|
|
175 |
|
|
|
176 |
return loss.item(), G_means |
|
|
177 |
|
|
|
178 |
# Set up figure. |
|
|
179 |
fig = plt.figure(figsize=(18, 7), facecolor="white", constrained_layout=True) |
|
|
180 |
ax_dict = fig.subplot_mosaic( |
|
|
181 |
[ |
|
|
182 |
["data", "preds"], |
|
|
183 |
["latent", "preds"], |
|
|
184 |
], |
|
|
185 |
) |
|
|
186 |
plt.show(block=False) |
|
|
187 |
|
|
|
188 |
for t in range(N_EPOCHS): |
|
|
189 |
loss, G_means = train(model, model.loss_fn, optimizer) |
|
|
190 |
|
|
|
191 |
if t % PRINT_EVERY == 0: |
|
|
192 |
print("Iter: {0:<10} LL {1:1.3e}".format(t, -loss)) |
|
|
193 |
|
|
|
194 |
G_means_test, _, F_samples_test, _, = model.forward( |
|
|
195 |
X_spatial={"expression": x_test}, |
|
|
196 |
view_idx=view_idx_test, |
|
|
197 |
Ns=Ns_test, |
|
|
198 |
prediction_mode=True, |
|
|
199 |
S=10, |
|
|
200 |
) |
|
|
201 |
|
|
|
202 |
curr_preds = torch.mean(F_samples_test["expression"], dim=0) |
|
|
203 |
|
|
|
204 |
callback_oned( |
|
|
205 |
model, |
|
|
206 |
X_train, |
|
|
207 |
Y_train, |
|
|
208 |
data_expression_ax=ax_dict["data"], |
|
|
209 |
latent_expression_ax=ax_dict["latent"], |
|
|
210 |
prediction_ax=ax_dict["preds"], |
|
|
211 |
X_aligned=G_means, |
|
|
212 |
X_test=X_test, |
|
|
213 |
Y_test_true=Y_test, |
|
|
214 |
Y_pred=curr_preds, |
|
|
215 |
X_test_aligned=G_means_test, |
|
|
216 |
) |
|
|
217 |
|
|
|
218 |
error_gpsa = np.mean((Y_test - curr_preds.detach().numpy()) ** 2) |
|
|
219 |
print("MSE, GPSA: {}".format(round(error_gpsa, 5))) |
|
|
220 |
|
|
|
221 |
errors_gpsa.append(error_gpsa) |
|
|
222 |
|
|
|
223 |
plt.close() |
|
|
224 |
|
|
|
225 |
results_df = pd.DataFrame( |
|
|
226 |
{"Union": errors_union, "Separate": errors_separate, "GPSA": errors_gpsa} |
|
|
227 |
) |
|
|
228 |
results_df_melted = pd.melt(results_df) |
|
|
229 |
|
|
|
230 |
plt.figure(figsize=(7, 5)) |
|
|
231 |
sns.boxplot(data=results_df_melted, x="variable", y="value", color="gray") |
|
|
232 |
plt.xlabel("") |
|
|
233 |
plt.ylabel("MSE") |
|
|
234 |
plt.tight_layout() |
|
|
235 |
plt.savefig("../../plots/one_d_prediction_comparison.png") |
|
|
236 |
plt.show() |
|
|
237 |
|
|
|
238 |
import ipdb |
|
|
239 |
|
|
|
240 |
ipdb.set_trace() |
|
|
241 |
|
|
|
242 |
# import matplotlib |
|
|
243 |
|
|
|
244 |
# font = {"size": LATEX_FONTSIZE} |
|
|
245 |
# matplotlib.rc("font", **font) |
|
|
246 |
# matplotlib.rcParams["text.usetex"] = True |
|
|
247 |
|
|
|
248 |
# fig = plt.figure(figsize=(10, 10)) |
|
|
249 |
# data_expression_ax = fig.add_subplot(211, frameon=False) |
|
|
250 |
# latent_expression_ax = fig.add_subplot(212, frameon=False) |
|
|
251 |
# callback_oned(model, X, Y, data_expression_ax, latent_expression_ax) |
|
|
252 |
|
|
|
253 |
# plt.tight_layout() |
|
|
254 |
# plt.savefig("../../plots/one_d_simulation.png") |
|
|
255 |
# plt.show() |
|
|
256 |
|
|
|
257 |
# import ipdb |
|
|
258 |
|
|
|
259 |
# ipdb.set_trace() |