Estoy programando una GAN simple para crear números a partir de un ruido aleatorio.
He logrado programar la red neuronal y funciona todo bien, pero no he encontrado como puedo hacer para ver la accuracy o la loss para poder verlas pintadas en un gráfico, con redes neuronales convolucionales por ejemplo, es más fácil, ya que en el .compile()
le defino las métricas que quiero usar, pero en este caso no se cómo puedo hacerlo.
Este es el código de mi red neuronal:
import os
import time
import imageio
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras, GradientTape
from tensorflow.keras.datasets import mnist
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Reshape, Conv2D, Flatten, Conv2DTranspose, BatchNormalization, LeakyReLU
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.optimizers import Adam
print('GPU available:', tf.config.list_physical_devices('GPU'))
print('tensorflow version:', tf.__version__)
(train_images, _), (_, _) = mnist.load_data()
train_images.shape
train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')
train_images = (train_images - 127.5) / 127.5
BUFFER_SIZE = 60000
BATCH_SIZE = 256
train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
def create_generator_model():
model = Sequential()
model.add(Dense(7 * 7 * 256, use_bias = False, input_shape = (100,)))
model.add(Reshape((7, 7, 256)))
model.add(Conv2DTranspose(128, (5, 5), strides = (2, 2), padding = 'same'))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha = 0.01))
model.add(Conv2DTranspose(64, (5, 5), strides = (1, 1), padding = 'same'))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha = 0.01))
model.add(Conv2DTranspose(1, (5, 5), strides = (2, 2), padding = 'same', activation = 'tanh'))
return model
generator = create_generator_model()
generator.summary()
noise_dim = 100
noise = tf.random.normal([1, noise_dim])
image_generated = generator(noise, training = False)
plt.imshow(image_generated[0, :, :, 0], cmap = 'gray')
def create_discriminator_model():
model = Sequential()
model.add(Conv2D(32, (5, 5), strides = (2, 2), padding = 'same', input_shape = [28, 28, 1]))
model.add(LeakyReLU(alpha = 0.01))
model.add(Conv2D(64, (5, 5), strides = (2, 2), padding = 'same'))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha = 0.01))
model.add(Conv2D(128, (5, 5), strides = (2, 2), padding = 'same'))
model.add(BatchNormalization())
model.add(LeakyReLU(alpha = 0.01))
model.add(Flatten())
model.add(Dense(1, activation = 'sigmoid'))
return model
discriminator = create_discriminator_model()
discriminator.summary()
decision = discriminator(image_generated)
print(decision)
generator_optimizer = Adam(learning_rate = 1e-4)
discriminator_optimizer = Adam(learning_rate = 1e-4)
@tf.function
def train_step(images):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with GradientTape() as gen_tape, GradientTape() as disc_tape:
images_generated = generator(noise, training = True)
real_output = discriminator(images, training = True)
fake_output = discriminator(images_generated, training = True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output)
gen_gradients = gen_tape.gradient(gen_loss, generator.trainable_variables)
disc_gradients = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
generator_optimizer.apply_gradients(zip(gen_gradients, generator.trainable_variables))
discriminator_optimizer.apply_gradients(zip(disc_gradients, discriminator.trainable_variables))
def generate_images(model, test_input):
predictions = model(test_input, training = False)
fig = plt.figure(figsize=(grid_size_x,grid_size_y))
for i in range(predictions.shape[0]):
plt.subplot(grid_size_x, grid_size_y, i + 1)
plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')
plt.axis('off')
plt.show()
grid_size_x = 10
grid_size_y = 10
seed = tf.random.normal([grid_size_x * grid_size_y, noise_dim])
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for image_batch in dataset:
train_step(image_batch)
generate_images(generator, seed)
print('EPOCH {} completed in {} segundos'.format(epoch + 1, time.time() - start))
generate_images(generator, seed)
EPOCHS = 100
history = train(train_dataset, EPOCHS)
¿Alguien sabe como puedo incorporar las métricas en este modelo para ver la precisión y la loss?
Estoy usando tensorflow 2.4 y python3