Spaces:
Runtime error
Runtime error
Upload model weights
Browse files- .gitattributes +1 -0
- app.py +26 -0
- blocks.py +81 -0
- cvae.py +127 -0
- model_data/checkpoint +2 -0
- model_data/cvae_trained.ckpt.data-00000-of-00001 +3 -0
- model_data/cvae_trained.ckpt.index +0 -0
- requirements.txt +6 -0
.gitattributes
CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
model_data/cvae_trained.ckpt.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from cvae import get_encoder, get_decoder, CVAE
|
2 |
+
import tensorflow as tf
|
3 |
+
import gradio as gr
|
4 |
+
import numpy as np
|
5 |
+
from matplotlib import cm
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
IMAGE_SIZE = (64, 64)
|
9 |
+
model = CVAE(get_encoder(), get_decoder(), latent_dim=512)
|
10 |
+
model.load_weights("model_data/cvae_trained.ckpt")
|
11 |
+
|
12 |
+
|
13 |
+
def generate_image(mean, variance):
|
14 |
+
|
15 |
+
sample = np.random.normal(mean, variance, size=512)
|
16 |
+
image = tf.reshape(model.decoder(sample[tf.newaxis, :]), IMAGE_SIZE)
|
17 |
+
image = [Image.fromarray(np.uint8(cm.gray(image)*255))]
|
18 |
+
|
19 |
+
return image
|
20 |
+
|
21 |
+
|
22 |
+
title = "variational-autoencoder-faces "
|
23 |
+
|
24 |
+
gr.Interface(fn=generate_image, outputs=gr.Gallery(), inputs=[gr.inputs.Slider(default=0, label="mean", maximum=10, minimum=-10, step=.1),
|
25 |
+
gr.inputs.Slider(default=1, label="variance", maximum=20, minimum=0, step=.1)],
|
26 |
+
title=title).launch(inline=False)
|
blocks.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tensorflow as tf
|
2 |
+
from typing import Any, Tuple
|
3 |
+
import tensorflow_addons as tfda
|
4 |
+
|
5 |
+
|
6 |
+
class ResidualBlock(tf.keras.layers.Layer):
|
7 |
+
|
8 |
+
def __init__(self, filter_num: int, filter_size: int, seed: Any = None, name=None, padding="default",
|
9 |
+
instance_normalization: bool = False):
|
10 |
+
super(ResidualBlock, self).__init__(name=name)
|
11 |
+
self.filter_num = filter_num
|
12 |
+
self.filter_size = filter_size
|
13 |
+
self.seed = seed
|
14 |
+
self.padding_type = padding
|
15 |
+
|
16 |
+
self.activation_1 = tf.keras.layers.Activation("linear", trainable=False)
|
17 |
+
if padding == "default":
|
18 |
+
self.conv_1 = tf.keras.layers.Conv2D(filters=self.filter_num, kernel_size=self.filter_size,
|
19 |
+
padding="same", trainable=True)
|
20 |
+
elif padding == "reflect":
|
21 |
+
self.pad_1 = ReflectionPadding2D(padding=(1, 1))
|
22 |
+
self.conv_1 = tf.keras.layers.Conv2D(filters=self.filter_num, kernel_size=self.filter_size,
|
23 |
+
padding="valid", trainable=True)
|
24 |
+
else:
|
25 |
+
raise RuntimeError("Non valid padding type.")
|
26 |
+
|
27 |
+
self.activation_2 = tf.keras.layers.Activation("relu")
|
28 |
+
|
29 |
+
if instance_normalization:
|
30 |
+
self.bn_1 = tfda.layers.InstanceNormalization(trainable=True)
|
31 |
+
self.bn_2 = tfda.layers.InstanceNormalization(trainable=True)
|
32 |
+
else:
|
33 |
+
self.bn_1 = tf.keras.layers.BatchNormalization(trainable=True)
|
34 |
+
self.bn_2 = tf.keras.layers.BatchNormalization(trainable=True)
|
35 |
+
|
36 |
+
if padding == "default":
|
37 |
+
self.conv_2 = tf.keras.layers.Conv2D(filters=self.filter_num, kernel_size=self.filter_size,
|
38 |
+
padding="same", trainable=True)
|
39 |
+
|
40 |
+
elif padding == "reflect":
|
41 |
+
self.pad_2 = ReflectionPadding2D(padding=(1, 1))
|
42 |
+
self.conv_2 = tf.keras.layers.Conv2D(filters=self.filter_num, kernel_size=self.filter_size,
|
43 |
+
padding="valid", trainable=True)
|
44 |
+
else:
|
45 |
+
raise RuntimeError("Non valid padding type.")
|
46 |
+
|
47 |
+
self.activation_3 = tf.keras.layers.Activation("relu")
|
48 |
+
|
49 |
+
def call(self, inputs, *args, **kwargs):
|
50 |
+
|
51 |
+
identity = self.activation_1(inputs)
|
52 |
+
x = identity
|
53 |
+
if self.padding_type == "reflect":
|
54 |
+
x = self.pad_1(x)
|
55 |
+
x = self.conv_1(x)
|
56 |
+
x = self.activation_2(x)
|
57 |
+
x = self.bn_1(x)
|
58 |
+
if self.padding_type == "reflect":
|
59 |
+
x = self.pad_2(x)
|
60 |
+
x = self.conv_2(x)
|
61 |
+
x = self.bn_2(x)
|
62 |
+
residual = tf.keras.layers.Add()([x, identity])
|
63 |
+
x = self.activation_3(residual)
|
64 |
+
return x
|
65 |
+
|
66 |
+
|
67 |
+
class ReflectionPadding2D(tf.keras.layers.Layer):
|
68 |
+
|
69 |
+
def __init__(self, padding: Tuple[int, int]):
|
70 |
+
super(ReflectionPadding2D, self).__init__()
|
71 |
+
self.pad_width, self.pad_height = padding
|
72 |
+
|
73 |
+
def call(self, inputs, *args, **kwargs):
|
74 |
+
padding_tensor = tf.constant([
|
75 |
+
[0, 0], # Batch
|
76 |
+
[self.pad_height, self.pad_height], # Height
|
77 |
+
[self.pad_width, self.pad_width], # Width
|
78 |
+
[0, 0] # Channels
|
79 |
+
])
|
80 |
+
|
81 |
+
return tf.pad(inputs, padding_tensor, mode="REFLECT")
|
cvae.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import keras.regularizers
|
4 |
+
import tensorflow as tf
|
5 |
+
from keras.layers import InputLayer, Conv2D, Flatten, BatchNormalization, Dense, UpSampling2D, Reshape, Dropout, Add
|
6 |
+
import keras.backend as tfkbk
|
7 |
+
import numpy as np
|
8 |
+
from blocks import ResidualBlock
|
9 |
+
from keras.layers import LeakyReLU, PReLU
|
10 |
+
|
11 |
+
INPUT_SHAPE = (64, 64)
|
12 |
+
LATENT_DIM = 512
|
13 |
+
|
14 |
+
|
15 |
+
def get_encoder():
|
16 |
+
encoder = tf.keras.Sequential(name="encoder")
|
17 |
+
|
18 |
+
encoder.add(InputLayer(input_shape=(*INPUT_SHAPE, 1)))
|
19 |
+
|
20 |
+
encoder.add(Conv2D(32, 3, activation=PReLU(), padding='same', kernel_initializer='he_uniform'))
|
21 |
+
encoder.add(Conv2D(32, 3, activation=PReLU(), padding='same', strides=2, kernel_initializer='he_uniform'))
|
22 |
+
encoder.add(Conv2D(64, 3, activation=PReLU(), padding='same', kernel_initializer='he_uniform'))
|
23 |
+
encoder.add(Conv2D(64, 3, activation=PReLU(), padding='same', strides=2, kernel_initializer='he_uniform'))
|
24 |
+
encoder.add(Conv2D(128, 3, activation=PReLU(), padding='same', kernel_initializer='he_uniform'))
|
25 |
+
encoder.add(Conv2D(128, 3, activation=PReLU(), padding='same', strides=2, kernel_initializer='he_uniform'))
|
26 |
+
|
27 |
+
encoder.add(Flatten())
|
28 |
+
|
29 |
+
encoder.add(Dense(LATENT_DIM * 2, activation=PReLU(), activity_regularizer=tf.keras.regularizers.L2(10e-6)))
|
30 |
+
|
31 |
+
return encoder
|
32 |
+
|
33 |
+
|
34 |
+
def get_decoder():
|
35 |
+
|
36 |
+
inputs = tf.keras.layers.Input(shape=[LATENT_DIM, ])
|
37 |
+
|
38 |
+
x = inputs
|
39 |
+
x = Dense(8 * 8 * 16, activation='relu')(x)
|
40 |
+
x = Dense(8 * 8 * 16, activation='relu')(x)
|
41 |
+
x = Reshape(target_shape=(8, 8, 16))(x)
|
42 |
+
|
43 |
+
x = UpSampling2D(2)(x)
|
44 |
+
x = Conv2D(128, 3, activation=LeakyReLU(), padding='same', kernel_initializer='he_uniform')(x)
|
45 |
+
x = ResidualBlock(128, 3, seed=42, name="res1", padding="reflect")(x)
|
46 |
+
x = ResidualBlock(128, 3, seed=42, name="res2", padding="reflect")(x)
|
47 |
+
|
48 |
+
x = UpSampling2D(2)(x)
|
49 |
+
x = Conv2D(64, 3, activation=LeakyReLU(), padding='same', kernel_initializer='he_uniform')(x)
|
50 |
+
x = ResidualBlock(64, 3, seed=42, name="res4", padding="reflect")(x)
|
51 |
+
x = ResidualBlock(64, 3, seed=42, name="res5", padding="reflect")(x)
|
52 |
+
|
53 |
+
x = UpSampling2D(2)(x)
|
54 |
+
x = Conv2D(32, 3, activation=LeakyReLU(), padding='same', kernel_initializer='he_uniform')(x)
|
55 |
+
x = ResidualBlock(32, 3, seed=42, name="res7", padding="reflect")(x)
|
56 |
+
x = ResidualBlock(32, 3, seed=42, name="res8", padding="reflect")(x)
|
57 |
+
|
58 |
+
x = Conv2D(1, 3, padding='same', kernel_initializer='he_uniform')(x)
|
59 |
+
|
60 |
+
return tf.keras.Model(inputs=inputs, outputs=x)
|
61 |
+
|
62 |
+
|
63 |
+
class CVAE(tf.keras.Model):
|
64 |
+
def __init__(self, encoder: tf.keras.models.Model, decoder: tf.keras.models.Model,
|
65 |
+
latent_dim, kl_weight=1, loss_fun='bce', include_regularization: bool = False):
|
66 |
+
super(CVAE, self).__init__()
|
67 |
+
self.kl_weight = kl_weight
|
68 |
+
self.latent_dim = latent_dim
|
69 |
+
self.loss_fun = loss_fun
|
70 |
+
self.encoder = encoder
|
71 |
+
self.decoder = decoder
|
72 |
+
self.kl_loss = 0
|
73 |
+
self.reconstruction_loss = 0
|
74 |
+
self.include_regularization = include_regularization
|
75 |
+
|
76 |
+
def call(self, inputs, training=None, mask=None):
|
77 |
+
z_mean, z_log_var = tf.split(self.encoder(inputs), num_or_size_splits=2, axis=1)
|
78 |
+
z = self.sampling(z_mean, z_log_var, self.latent_dim)
|
79 |
+
# z_mean, z_log_var, z = self.encoder(inputs)
|
80 |
+
outputs = self.decoder(z)
|
81 |
+
|
82 |
+
if training:
|
83 |
+
regularization_loss = tf.math.reduce_sum(self.encoder.losses)
|
84 |
+
|
85 |
+
if self.loss_fun == 'elbo':
|
86 |
+
cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=outputs, labels=inputs)
|
87 |
+
logpx_z = -tf.reduce_sum(cross_ent, axis=[1, 2, 3])
|
88 |
+
logpz = self.log_normal_pdf(z, 0., 0.)
|
89 |
+
logqz_x = self.log_normal_pdf(z, z_mean, z_log_var)
|
90 |
+
vae_loss = -tf.reduce_mean(logpx_z + logpz - logqz_x)
|
91 |
+
else:
|
92 |
+
kl_loss = 1 + z_log_var - tf.math.square(z_mean) - tf.math.exp(z_log_var)
|
93 |
+
kl_loss = tf.math.reduce_sum(kl_loss, axis=-1)
|
94 |
+
kl_loss *= -0.5 * self.kl_weight
|
95 |
+
self.kl_loss = kl_loss
|
96 |
+
if self.loss_fun == 'mse':
|
97 |
+
reconstruction_loss = tf.keras.metrics.mean_squared_error(tfkbk.flatten(inputs),
|
98 |
+
tfkbk.flatten(outputs))
|
99 |
+
elif self.loss_fun == 'bce':
|
100 |
+
reconstruction_loss = tf.keras.metrics.binary_crossentropy(tfkbk.flatten(inputs),
|
101 |
+
tfkbk.flatten(outputs))
|
102 |
+
else:
|
103 |
+
raise ValueError
|
104 |
+
|
105 |
+
reconstruction_loss *= (inputs.shape[1] * inputs.shape[1])
|
106 |
+
self.reconstruction_loss = reconstruction_loss
|
107 |
+
vae_loss = tf.math.reduce_mean(reconstruction_loss + kl_loss)
|
108 |
+
|
109 |
+
if self.include_regularization:
|
110 |
+
vae_loss += regularization_loss
|
111 |
+
|
112 |
+
self.add_loss(vae_loss)
|
113 |
+
return outputs
|
114 |
+
|
115 |
+
@staticmethod
|
116 |
+
def sampling(z_mean, z_log_var, latent_dim):
|
117 |
+
batch = tf.shape(z_mean)[0]
|
118 |
+
epsilon = tf.keras.backend.random_normal(shape=(batch, latent_dim))
|
119 |
+
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
|
120 |
+
|
121 |
+
@staticmethod
|
122 |
+
def log_normal_pdf(sample, mean, logvar, raxis=1):
|
123 |
+
log2pi = tf.math.log(2. * np.pi)
|
124 |
+
return tf.reduce_sum(
|
125 |
+
-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi),
|
126 |
+
axis=raxis)
|
127 |
+
|
model_data/checkpoint
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
model_checkpoint_path: "cvae_trained.ckpt"
|
2 |
+
all_model_checkpoint_paths: "cvae_trained.ckpt"
|
model_data/cvae_trained.ckpt.data-00000-of-00001
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a38425718ad0bb40c171e698c686e9956340f3f3711751df0ab199a36bcdd8a5
|
3 |
+
size 137170643
|
model_data/cvae_trained.ckpt.index
ADDED
Binary file (19.1 kB). View file
|
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
tensorflow~=2.10.0
|
2 |
+
tensorflow_addons
|
3 |
+
gradio~=3.17.1
|
4 |
+
numpy~=1.21.6
|
5 |
+
Pillow~=8.4.0
|
6 |
+
keras~=2.10.0
|