Skip to content

Commit c751e5d

Browse files
giovannivolpeBenjaminMidtvedtgithub-actions[bot]JesusPinedaCHenrik-KM
authored
Release DeepTrack2 1.6.0 (#191)
* chore: autopublish 2022-07-26T13:54:44Z * Remove create-badges job * Delete test.py * Add multi-head masked attention * Update multi-head gated attention to match parent layer * Update documentation * Test multi-head masked attention * allow gated attention layers to use bias * test bias in gated attention layers * set return_attention_weights to False to avoid multi-outputs Use MultiHeadSelfAttention and MultiHeadGatedSelfAttention if want to return the attention weights * reformat gnns/layers.py This commit adds new message-passing graph layers (MPN) and graph convolutional layers to dt, including vanilla MPN, GRUMPN, Masked-attention FGNN, and GraphTransformer. * Update layers.py * Update test_layers.py * Update models.py * Update test_models.py * Update test_models.py * Fix indexing problems related to tf.gather * Allow multi-inputs in ContinuousGenerator * Fix bad conversion to integer * version bump * Fix phase correction at focus and offset calculation * Fix phase correction in propagation * Fix mie phase out of foucs * Fix mie phase out of foucs * Update README.md * Bm/version 1.4.0 (#137) * Update layers.py * Update convolutional.py Transformer-based models can now be reused and expanded quickly and easily * Update documentation * Update Transformer-based models * Delete classifying_MNIST_vit_tutorial.ipynb * Create classifying_MNIST_vit_tutorial.ipynb * Update datasets.py * Allows kwargs as inputs in single_layer_call * Update embeddings.py * masked transformers * reformat transformer models * Create trajectory_analysis_tutorial.ipynb * Add Variational autoencoders * Add variational autoencoders * Update vae.py * Create MNIST_VAE_tutorial.ipynb * Update MNIST_VAE_tutorial.ipynb * Create folder for course examples * Update README.md * Update README.md * Update examples * Update README.md * Update README.md * Update MNIST VAE examples * Added MLP regression example * Update README.md * Create image_segmentation_Unet.ipynb * Update README.md * Documented and tested cell_counting_tutorial.ipynb * improve dnn example * Shift variant mie * Position mie scatterer correctly * implement set z * implement mnist v1 * implement z dependence * remove logging * Implement flattening methods * Implement pooling and resizing * Implement TensorflowDataset * Finalize MNIST * Implement Malaria classification * alpha0 release * fix batchsize in fit * implement dataset.take * Implement datasets * fix phase in mie * Fix mie positioning and focusing * Commit to new branch * add tensorflow datasets dependence * remove test Co-authored-by: Jesús Pineda <[email protected]> Co-authored-by: Jesús Pineda <[email protected]> Co-authored-by: Benjamin Midtvedt <[email protected]> Co-authored-by: Ccx55 <[email protected]> * Add tensorflow datasets to the list of dependencies. * Read requirements.txt into setup.py * remove sphinx from build * remove create badges * Create CITATION.cff * Create .zenodo.json * Update transformer models * Update pint_definition.py * Update requirements.txt * create TimeDistributed CNN * small fixes to lodestar * Update layers.py * Update test_layers.py * remove direct getter of properties * Update scatterers.py Coherence length fix for MieScatterer * Update scatterers.py Added coherence length to the conversion table * mie phase fix * removed pydeepimagej from deps * Change loss input order of CGAN and PCGAN * Create dmdataset (dataset for graph-level regression tasks) * Update gnns/__init__.py * Add detection_linking_hela dataset * Update dmdataset.py * Create the regression_diffusion_landscape * Update scatterers.py CuPy fix for coherence length * Update test_scatterers.py Added a new method for testing MieSphere when coherence length parameter is provided. * Update augmentations.py * Update test_scatterers.py * Update test_scatterers.py * Create endothelial_vs dataset * Update layers.py * Update utils.py * Update docs link * Update README.md * version bump * version bump * Update README.md * Update README.md * Update graphs.py * Update test_generators.py * Update generators.py * fix test * Update vae.py * Bugfix in endothelial_vs dataset * Fix issue with repeated oneof-features (#169) * Update cell_migration_analysis.ipynb * Update features.py (#189) * added WAE (both MMD and GAN) (#185) * added deterministic wae_gan, slightly modified vae (input size)) * changes to VAE, WAE_GAN, and GAN Implemented proposed changes to GAN, VAE, WAE_GAN: - optimizers of WAE_GAN as input parameters by overriding the compile method. - included documentation of input parameters for VAE and WAE_GAN. - WAE_GAN: different learning rates for the autoencoder and the discriminator, 1e-3 and 5e-4, respectively as in the original paper. - included a unit test for WAE_GAN, VAE, and GAN. - removed @as_KerasModel from GAN. - formatted the code for compatibility. * Update test_models.py * fixed typo * extra fixes * WAE generalized allows WAE-GAN and WAE-MMD * fixes * check unit test * compatibility issue removed match for compatibility, replaced with if * test unit corrected assert in test unit for GAN, VAE. and WAE * fixed dimension in test_models * added compile for GAN and WAE in test_model * defined call in gan * fixed input size in GAN --------- Co-authored-by: BenjaminMidtvedt <[email protected]> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Jesús Pineda <[email protected]> Co-authored-by: Benjamin Midtvedt <[email protected]> Co-authored-by: Jesús Pineda <[email protected]> Co-authored-by: Ccx55 <[email protected]> Co-authored-by: Harshith Bachimanchi <[email protected]> Co-authored-by: gideon <[email protected]> Co-authored-by: Benjamin Midtvedt <[email protected]> Co-authored-by: Carlo <[email protected]>
1 parent cdb6097 commit c751e5d

File tree

7 files changed

+436
-58
lines changed

7 files changed

+436
-58
lines changed

deeptrack/features.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1637,7 +1637,7 @@ def _process_and_get(self, images, **kwargs):
16371637
p0[0] = np.max([p0[0], 0])
16381638
p0[1] = np.max([p0[1], 0])
16391639

1640-
p0 = p0.astype(np.int)
1640+
p0 = p0.astype(int)
16411641

16421642
output_slice = output[
16431643
p0[0] : p0[0] + labelarg.shape[0],

deeptrack/models/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from .gans import *
88
from .gnns import *
99
from .vaes import *
10+
from .waes import *
1011

1112
# from .mrcnn import *
1213
# from .yolov1 import *

deeptrack/models/gans/gan.py

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,24 @@
33

44
layers = tf.keras.layers
55

6-
7-
@as_KerasModel
86
class GAN(tf.keras.Model):
7+
"""Generative Adversarial Network (GAN) model.
8+
9+
Parameters:
10+
discriminator: keras model, optional
11+
The discriminator network.
12+
generator: keras model, optional
13+
The generator network.
14+
latent_dim: int, optional
15+
Dimension of the latent space for random vectors.
16+
"""
17+
918
def __init__(self, discriminator=None, generator=None, latent_dim=128):
1019
super(GAN, self).__init__()
1120

21+
# Initialize discriminator and generator, or use default if not provided
1222
if discriminator is None:
1323
discriminator = self.default_discriminator()
14-
1524
if generator is None:
1625
generator = self.default_generator()
1726

@@ -21,9 +30,13 @@ def __init__(self, discriminator=None, generator=None, latent_dim=128):
2130

2231
def compile(self, d_optimizer, g_optimizer, loss_fn):
2332
super(GAN, self).compile()
33+
34+
# Set optimizers and loss function for training
2435
self.d_optimizer = d_optimizer
2536
self.g_optimizer = g_optimizer
2637
self.loss_fn = loss_fn
38+
39+
# Define metrics to track during training
2740
self.d_loss_metric = tf.keras.metrics.Mean(name="d_loss")
2841
self.g_loss_metric = tf.keras.metrics.Mean(name="g_loss")
2942

@@ -36,17 +49,18 @@ def train_step(self, real_images):
3649
batch_size = tf.shape(real_images)[0]
3750
random_latent_vectors = tf.random.normal(shape=(batch_size, self.latent_dim))
3851

39-
# Decode them to fake images
52+
# Generate fake images using the generator
4053
generated_images = self.generator(random_latent_vectors)
4154

42-
# Combine them with real images
55+
# Combine real and fake images
4356
combined_images = tf.concat([generated_images, real_images], axis=0)
4457

45-
# Assemble labels discriminating real from fake images
58+
# Create labels for real and fake images
4659
labels = tf.concat(
4760
[tf.ones((batch_size, 1)), tf.zeros((batch_size, 1))], axis=0
4861
)
49-
# Add random noise to the labels - important trick!
62+
63+
# Add random noise to labels to improve stability
5064
labels += 0.05 * tf.random.uniform(tf.shape(labels))
5165

5266
# Train the discriminator
@@ -58,14 +72,13 @@ def train_step(self, real_images):
5872
zip(grads, self.discriminator.trainable_weights)
5973
)
6074

61-
# Sample random points in the latent space
75+
# Generate new random latent vectors
6276
random_latent_vectors = tf.random.normal(shape=(batch_size, self.latent_dim))
6377

64-
# Assemble labels that say "all real images"
78+
# Create labels indicating "all real images" for generator training
6579
misleading_labels = tf.zeros((batch_size, 1))
6680

67-
# Train the generator (note that we should *not* update the weights
68-
# of the discriminator)!
81+
# Train the generator while keeping discriminator weights fixed
6982
with tf.GradientTape() as tape:
7083
predictions = self.discriminator(self.generator(random_latent_vectors))
7184
g_loss = self.loss_fn(misleading_labels, predictions)
@@ -75,12 +88,19 @@ def train_step(self, real_images):
7588
# Update metrics
7689
self.d_loss_metric.update_state(d_loss)
7790
self.g_loss_metric.update_state(g_loss)
91+
92+
# Return updated loss metrics
7893
return {
7994
"d_loss": self.d_loss_metric.result(),
8095
"g_loss": self.g_loss_metric.result(),
8196
}
8297

98+
def call(self, inputs):
99+
# Run generator
100+
return self.generator(inputs)
101+
83102
def default_generator(self, latent_dim=128):
103+
# Define the default generator architecture
84104
return tf.keras.Sequential(
85105
[
86106
tf.keras.Input(shape=(latent_dim,)),
@@ -98,6 +118,7 @@ def default_generator(self, latent_dim=128):
98118
)
99119

100120
def default_discriminator(self):
121+
# Define the default discriminator architecture
101122
return tf.keras.Sequential(
102123
[
103124
tf.keras.Input(shape=(64, 64, 3)),
@@ -112,4 +133,4 @@ def default_discriminator(self):
112133
layers.Dense(1, activation="sigmoid"),
113134
],
114135
name="discriminator",
115-
)
136+
)

deeptrack/models/vaes/vae.py

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,39 @@
11
import tensorflow as tf
22
from tensorflow.keras import layers
3-
43
from ..utils import as_KerasModel
54

65

7-
@as_KerasModel
86
class VAE(tf.keras.Model):
7+
"""Variational Autoencoder (VAE) model.
8+
9+
Parameters:
10+
encoder: keras model, optional
11+
The encoder network.
12+
decoder: keras model, optional
13+
The decoder network.
14+
latent_dim: int, optional
15+
Dimension of the latent space.
16+
"""
17+
918
def __init__(self, encoder=None, decoder=None, latent_dim=2, **kwargs):
10-
super().__init__(**kwargs)
19+
super(VAE, self).__init__(**kwargs)
1120

12-
# Dimensionality of the latent space
21+
# Define encoder latent dimension
1322
self.latent_dim = latent_dim
1423

24+
# Initialize encoder and decoder, or use defaults
1525
if encoder is None:
1626
self.encoder = self.default_encoder()
1727

1828
if decoder is None:
1929
self.decoder = self.default_decoder()
2030

2131
def train_step(self, data):
22-
2332
data, _ = data
2433

34+
# Gradient tape for automatic differentiation
2535
with tf.GradientTape() as tape:
36+
# Encode input data and sample from latent space.
2637
# The encoder outputs the mean and log of the variance of the
2738
# Gaussian distribution. The log of the variance is computed
2839
# instead of the variance for numerical stability.
@@ -32,42 +43,37 @@ def train_step(self, data):
3243
epsilon = tf.random.normal(shape=tf.shape(z_mean))
3344
z = z_mean + tf.exp(0.5 * z_log_var) * epsilon
3445

35-
# Reconstruct the input image
46+
# Decode latent samples and compute reconstruction loss
3647
rdata = self.decoder(z)
37-
38-
# Reconstruction loss
3948
rloss = self.loss(data, rdata)
4049

41-
# KL divergence loss
42-
kl_loss = -0.5 * (
43-
1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var)
44-
)
50+
# Compute KL divergence loss
51+
kl_loss = -0.5 * (1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var))
4552
kl_loss = tf.reduce_mean(tf.reduce_sum(kl_loss, axis=1))
4653

47-
# Total loss
54+
# Compute total loss
4855
loss = rloss + kl_loss
4956

50-
# Compute gradients
57+
# Compute gradients and update model weights
5158
grads = tape.gradient(loss, self.trainable_weights)
59+
self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
5260

53-
# Update weights
54-
self.optimizer.apply_gradients(
55-
zip(grads, self.trainable_weights),
56-
)
57-
58-
# Update metrics
61+
# Update metrics for monitoring
5962
self.compiled_metrics.update_state(data, rdata)
6063

64+
# Return loss values for visualization
6165
return {
6266
"loss": loss,
6367
"reconstruction_loss": rloss,
6468
"kl_loss": kl_loss,
6569
}
6670

6771
def call(self, inputs):
72+
# Use encoder to obtain latent representation
6873
return self.encoder(inputs)
6974

7075
def default_encoder(self):
76+
# Define the default encoder architecture
7177
return tf.keras.Sequential(
7278
[
7379
tf.keras.Input(shape=(28, 28, 1)),
@@ -88,14 +94,13 @@ def default_encoder(self):
8894
layers.Flatten(),
8995
layers.Dense(16),
9096
layers.LeakyReLU(alpha=0.2),
91-
layers.Dense(
92-
self.latent_dim + self.latent_dim, name="z_mean_log_var"
93-
),
97+
layers.Dense(self.latent_dim + self.latent_dim, name="z_mean_log_var"),
9498
],
9599
name="encoder",
96100
)
97101

98102
def default_decoder(self):
103+
# Define the default decoder architecture
99104
return tf.keras.Sequential(
100105
[
101106
tf.keras.Input(shape=(self.latent_dim,)),

deeptrack/models/waes/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .wae import *

0 commit comments

Comments
 (0)