-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparameter_fitting_Denoising_to_CT.py
More file actions
350 lines (329 loc) · 10.9 KB
/
Copy pathparameter_fitting_Denoising_to_CT.py
File metadata and controls
350 lines (329 loc) · 10.9 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""
This script provides the parameter fitting routines for Experiment 2 of the paper.
A description how to use this script (and to define the input arguments) is given in the readme file
within the section "Reproduce Denoising to CT (Experiment 2)".
"""
from priors import (
ParameterLearningWrapper,
NETT,
WCRR,
ICNNPrior,
IDCNNPrior,
LSR,
TDV,
LocalAR,
EPLL,
PatchNR,
)
from training_methods import bilevel_training
from deepinv.optim.utils import GaussianMixtureModel
import torch
from operators import get_evaluation_setting
from dataset import get_dataset
from evaluation import evaluate
import argparse
import os
import logging
import datetime
import numpy as np
if torch.backends.mps.is_available():
device = "mps"
elif torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
parser = argparse.ArgumentParser(description="Choosing evaluation setting")
parser.add_argument("--evaluation_mode", type=str, default="bilevel-IFT")
parser.add_argument("--regularizer_name", type=str, default="CRR")
parser.add_argument("--load_fitted_parameters", type=bool, default=False)
inp = parser.parse_args()
problem = "CT"
regularizer_name = inp.regularizer_name
evaluation_mode = inp.evaluation_mode
load_fitted_parameters = inp.load_fitted_parameters
mode = "IFT"
lmbd_initial_guess = 60
lr = 0.1
if regularizer_name == "CRR":
reg = WCRR(
sigma=0.1,
weak_convexity=0.0,
).to(device)
elif regularizer_name == "WCRR":
reg = WCRR(
sigma=0.1,
weak_convexity=1.0,
).to(device)
elif regularizer_name == "ICNN":
reg = ICNNPrior(in_channels=1, channels=32, device=device, kernel_size=5).to(device)
elif regularizer_name == "IDCNN":
reg = IDCNNPrior(in_channels=1, channels=32, device=device, kernel_size=5).to(
device
)
elif regularizer_name == "LAR":
if evaluation_mode == "AR":
output_factor = (
362**2 / 321**2
) # due to the mean reduction the regularization constant must be adapted for different image sizes
reg = LocalAR(
in_channels=1,
pad=True,
use_bias=True,
n_patches=-1,
output_factor=output_factor,
).to(device)
else:
reg = LocalAR(
in_channels=1,
pad=True,
use_bias=False,
n_patches=-1,
reduction="sum",
output_factor=1 / 142**2,
pretrained=None,
).to(device)
elif regularizer_name == "TDV":
config = dict(
in_channels=1,
num_features=32,
multiplier=1,
num_mb=3,
num_scales=3,
zero_mean=True,
)
reg = TDV(**config).to(device)
elif regularizer_name == "LSR":
reg = LSR(
nc=[32, 64, 128, 256], pretrained_denoiser=False, alpha=1.0, sigma=3e-2
).to(device)
elif regularizer_name == "EPLL":
weights_filepath = f"weights/gmm_Denoising.pt"
setup_data = torch.load(weights_filepath)
patch_size = setup_data["patch_size"]
n_gmm_components = setup_data["n_gmm_components"]
GMM = GaussianMixtureModel(n_gmm_components, patch_size**2, device=device)
GMM.load_state_dict(setup_data["weights"])
regularizer = EPLL(
device=device,
patch_size=patch_size,
channels=1,
n_gmm_components=n_gmm_components,
GMM=GMM,
pad=True,
batch_size=30000,
)
lmbd = 500.0
lmbd_guesses = [0.8 * lmbd + i * (0.4 * lmbd) / 9 for i in range(10)]
elif regularizer_name == "PatchNR":
weights_filepath = f"weights/patchnr/patchnr_6x6_BSD500_fitted.pt"
weights = torch.load(weights_filepath, map_location=device)
regularizer = PatchNR(
patch_size=6,
channels=1,
num_layers=5,
sub_net_size=weights["patchnr_subnetsize"],
device=device,
n_patches=weights["n_patches"],
pretrained=None,
pad=True,
)
regularizer.load_state_dict(weights["weights"])
min_lmbd = 280.0
max_lmbd = 320.0
lmbd_guesses = np.linspace(min_lmbd, max_lmbd, 15)
elif regularizer_name == "NETT":
reg = NETT(
in_channels=1, out_channels=1, hidden_channels=64, padding_mode="zeros"
).to(device)
if regularizer_name in ["EPLL", "PatchNR"]:
pass
elif (
evaluation_mode == "bilevel-IFT"
or evaluation_mode == "bilevel-JFB"
or evaluation_mode == "Score"
or evaluation_mode == "NETT"
):
if regularizer_name == "IDCNN":
mode = "JFB"
if regularizer_name == "LAR":
lr = 0.01
if regularizer_name == "LSR":
lr = 0.1
regularizer = ParameterLearningWrapper(reg, device=device)
if evaluation_mode == "Score":
if regularizer_name == "TDV":
lr = 0.05
if regularizer_name == "IDCNN":
lr = 0.01
if regularizer_name == "LSR":
mode = "JFB"
lr = 0.05
if regularizer_name == "LAR": # LAR has no IFT weights
mode = "JFB"
lr = 0.005
weights = torch.load(
f"weights/score_parameter_fitting_for_Denoising/{regularizer_name}_fitted_parameters_with_JFB_for_Denoising.pt",
map_location=device,
)
else:
weights = torch.load(
f"weights/score_parameter_fitting_for_Denoising/{regularizer_name}_fitted_parameters_with_IFT_for_Denoising.pt",
map_location=device,
)
elif evaluation_mode == "bilevel-IFT":
weights = torch.load(
f"weights/bilevel_Denoising/{regularizer_name}_bilevel_IFT_for_Denoising.pt",
map_location=device,
)
elif evaluation_mode == "bilevel-JFB":
weights = torch.load(
f"weights/bilevel_Denoising/{regularizer_name}_bilevel_JFB_for_Denoising.pt",
map_location=device,
)
elif evaluation_mode == "NETT":
weights = torch.load(
f"weights/NETT_Denoising_fitted.pt",
map_location=device,
)
regularizer.load_state_dict(weights)
elif evaluation_mode == "AR":
regularizer = ParameterLearningWrapper(reg, device=device)
weights = torch.load(
f"weights/adversarial_Denoising/{regularizer_name}_adversarial_for_Denoising_fitted.pt",
map_location=device,
)
regularizer.load_state_dict(weights)
else:
raise ValueError("Unknown evaluation mode!")
logger = logging.getLogger(__name__)
logging.basicConfig(
filename="log_parameter_fitting_"
+ regularizer_name
+ "_"
+ evaluation_mode
+ "_"
+ str(datetime.datetime.now())
+ ".log",
level=logging.INFO,
format="%(asctime)s: %(message)s",
)
if not os.path.isdir("weights"):
os.mkdir("weights")
if not os.path.isdir(f"weights/Denoising_to_CT"):
os.mkdir(f"weights/Denoising_to_CT")
dataset, physics, data_fidelity = get_evaluation_setting(problem, device)
validation_dataset = get_dataset("LoDoPaB_val")
validation_dataloader = torch.utils.data.DataLoader(
validation_dataset, batch_size=5, shuffle=False, drop_last=False, num_workers=8
)
if isinstance(regularizer, ParameterLearningWrapper):
wrapped_regularizer = regularizer
else:
wrapped_regularizer = ParameterLearningWrapper(regularizer, device=device)
if load_fitted_parameters:
if regularizer_name == "EPLL":
setup_data = torch.load(f"weights/Denoising_to_CT/EPLL", map_location=device)
regularizer.GMM.load_state_dict(setup_data["weights"])
lmbd_initial_guess = setup_data["lambda"]
wrapped_regularizer = regularizer
elif regularizer_name == "PatchNR":
weights = torch.load(f"weights/Denoising_to_CT/PatchNR", map_location=device)
regularizer.load_state_dict(weights["weights"])
lmbd_initial_guess = weights["lambda"]
wrapped_regularizer = regularizer
else:
wrapped_regularizer.load_state_dict(
torch.load(
f"weights/Denoising_to_CT/{regularizer_name}_with_{evaluation_mode}",
map_location=device,
)
)
elif regularizer_name in ["EPLL", "PatchNR"]:
best_lmbd = -1
best_psnr = -999
for lmbd in lmbd_guesses:
print(lmbd)
mean_psnr, x_out, y_out, recon_out = evaluate(
physics=physics,
data_fidelity=data_fidelity,
dataset=validation_dataset,
regularizer=regularizer,
lmbd=lmbd,
NAG_step_size=1e-3,
NAG_max_iter=3000,
NAG_tol=1e-4,
only_first=False,
adaptive_range=True,
device=device,
adam=True,
logger=logger,
)
if mean_psnr > best_psnr:
best_psnr = mean_psnr
best_lmbd = lmbd
lmbd_initial_guess = best_lmbd
wrapped_regularizer = regularizer
if regularizer_name == "EPLL":
setup_data["lambda"] = best_lmbd
torch.save(setup_data, f"weights/Denoising_to_CT/EPLL")
elif regularizer_name == "PatchNR":
weights["lambda"] = best_lmbd
torch.save(weights, f"weights/Denoising_to_CT/PatchNR")
else:
for p in wrapped_regularizer.parameters():
p.requires_grad_(False)
wrapped_regularizer.alpha.requires_grad_(True)
if not regularizer_name == "NETT":
wrapped_regularizer.scale.requires_grad_(True)
# parameter search
wrapped_regularizer, loss_train, loss_val, psnr_train, psnr_val = bilevel_training(
wrapped_regularizer,
physics,
data_fidelity,
lmbd_initial_guess,
validation_dataloader,
validation_dataloader,
epochs=100,
mode=mode,
lower_level_step_size=1e-1,
lower_level_max_iter=1000,
lower_level_tol_train=1e-4,
lower_level_tol_val=1e-4,
lr=lr,
momentum_optim=(0.5, 0.9),
lr_decay=0.999,
device=device,
verbose=False,
validation_epochs=100,
dynamic_range_psnr=True,
logger=logger,
)
torch.save(
wrapped_regularizer.state_dict(),
f"weights/Denoising_to_CT/{regularizer_name}_with_{evaluation_mode}",
)
if regularizer_name not in ["EPLL", "PatchNR"]:
print("Final alpha: ", wrapped_regularizer.alpha)
print("Final scale: ", wrapped_regularizer.scale)
wrapped_regularizer.alpha.requires_grad_(False)
wrapped_regularizer.scale.requires_grad_(False)
only_first = False
torch.random.manual_seed(0) # make results deterministic
print(lmbd_initial_guess)
mean_psnr, x_out, y_out, recon_out = evaluate(
physics=physics,
data_fidelity=data_fidelity,
dataset=dataset,
regularizer=wrapped_regularizer,
lmbd=lmbd_initial_guess,
step_size=1e-3 if regularizer_name in ["EPLL", "PatchNR"] else 1e-2,
max_iter=3000 if regularizer_name in ["EPLL", "PatchNR"] else 1000,
tol=1e-4,
only_first=only_first,
device=device,
verbose=True,
adam=regularizer_name in ["EPLL", "PatchNR"],
adaptive_range=True,
)
print("Mean PSNR: ", mean_psnr)
logger.info("Mean PSNR: " + str(mean_psnr))