<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Machine Learning and Data Science Applications | Sage Woodard</title>
    <description>Developing machine learning applications that transform data into actionable insights, solve complex problems, and drive meaningful change.</description>
    <link>https://sagewoodard.github.io/</link>
    <atom:link href="https://sagewoodard.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 29 Nov 2024 05:30:48 +0000</pubDate>
    <lastBuildDate>Fri, 29 Nov 2024 05:30:48 +0000</lastBuildDate>
    <generator>Jekyll v3.10.0</generator>
    
      <item>
        <title>Comparing GANs and Stable Diffusion Models for Satellite Imagery</title>
        <description>&lt;p&gt;&lt;img src=&quot;/images/gan-vs-sdm-cover.png&quot; alt=&quot;GAN vs SDM Cover&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;project-overview&quot;&gt;Project Overview&lt;/h3&gt;

&lt;p&gt;This project explores the performance differences between Generative Adversarial Networks (GANs) and Stable Diffusion Models (SDM) for generating terrain imagery from satellite data.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;key-highlights&quot;&gt;Key Highlights&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Comparison Metrics:&lt;/strong&gt; Evaluation was based on Frechet Inception Distance (FID), loss metrics, and visual inspection.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Results:&lt;/strong&gt; Stable Diffusion was identified as the more promising model for generating realistic terrain images.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Future Work:&lt;/strong&gt; Incorporate higher-resolution datasets to improve the realism of generated terrain images. Explore a hybrid pipeline combining GANs for structural layout generation and Stable Diffusion for detailed refinement. Additional enhancements will be implemented using PyTorch.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;project-paper&quot;&gt;Project Paper&lt;/h3&gt;

&lt;iframe src=&quot;/gan-vs-sdm-project/gan-vs-sdm-paper.pdf&quot; width=&quot;100%&quot; height=&quot;600px&quot; style=&quot;border: none;&quot;&gt;
    Your browser does not support iframes. You can &lt;a href=&quot;/gan-vs-sdm-project/gan-vs-sdm-paper.pdf&quot;&gt;view the paper here&lt;/a&gt;.
&lt;/iframe&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;gan-model-code&quot;&gt;GAN Model Code&lt;/h3&gt;

&lt;div class=&quot;code-viewer&quot;&gt;
    &lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;
    # -*- coding: utf-8 -*-
&quot;&quot;&quot;GAN_11_2024.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1y7NJzVZwzhq-dVSD7C0Rc0h23lnh29CI
&quot;&quot;&quot;

# Mount Google Drive
from google.colab import drive
drive.mount(&apos;/content/drive&apos;)

# Set the dataset path
data_dir = &apos;/content/drive/MyDrive/EuroSAT/Forest&apos;

# Load the dataset as a TensorFlow Dataset
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input
from scipy.linalg import sqrtm
import matplotlib.pyplot as plt
import numpy as np

# Parameters for image preprocessing
IMG_SIZE = 64
BATCH_SIZE = 64 # Changed from 32 for stabilization
noise_dim = 100

# Load images from the directory
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    label_mode=None, # No labels are required for unsupervised learning
    image_size=(IMG_SIZE, IMG_SIZE),
    batch_size=BATCH_SIZE
)

# Normalize images to [-1, 1], as required for GANs
train_dataset = train_dataset.map(lambda x: (x / 127.5) - 1)
train_dataset = train_dataset.shuffle(buffer_size=1000)

# Define the generator model
def build_generator():
  model = tf.keras.Sequential()
  model.add(layers.Dense(8 * 8 * 256, use_bias=False, input_shape=(100,)))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Reshape((8, 8, 256)))
  model.add(layers.Conv2DTranspose(128, (5, 5), strides=(2, 2), padding=&apos;same&apos;, use_bias=False))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding=&apos;same&apos;, use_bias=False))
  model.add(layers.BatchNormalization())
  model.add(layers.LeakyReLU())

  model.add(layers.Conv2DTranspose(3, (5, 5), strides=(2, 2), padding=&apos;same&apos;, use_bias=False, activation=&apos;tanh&apos;))
  return model

# Define the discriminator model
def build_discriminator():
  model = tf.keras.Sequential()
  model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding=&apos;same&apos;, input_shape=[IMG_SIZE, IMG_SIZE, 3]))
  model.add(layers.LeakyReLU())
  model.add(layers.Dropout(0.3))

  model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding=&apos;same&apos;))
  model.add(layers.LeakyReLU())
  model.add(layers.Dropout(0.3))

  model.add(layers.Flatten())
  model.add(layers.Dense(1))
  return model

# FID calculation functions
def calculate_fid(real_images, generated_images):
    # Resize images to match the InceptionV3 input requirements
    real_images_resized = tf.image.resize(real_images, (75, 75))
    generated_images_resized = tf.image.resize(generated_images, (75, 75))

    # Load the InceptionV3 model for feature extraction
    inception_model = InceptionV3(include_top=False, pooling=&apos;avg&apos;, input_shape=(75, 75, 3))

    # Preprocess images for InceptionV3
    real_images_resized = preprocess_input((real_images_resized + 1) * 127.5)  # Rescale to [0, 255]
    generated_images_resized = preprocess_input((generated_images_resized + 1) * 127.5)

    # Extract features using the InceptionV3 model
    act1 = inception_model.predict(real_images_resized)
    act2 = inception_model.predict(generated_images_resized)

    # Calculate the mean and covariance of the features
    mu1, sigma1 = np.mean(act1, axis=0), np.cov(act1, rowvar=False)
    mu2, sigma2 = np.mean(act2, axis=0), np.cov(act2, rowvar=False)

    # Calculate the squared difference between the means
    ssdiff = np.sum((mu1 - mu2)**2.0)

    # Calculate the square root of the product of the covariances
    covmean = sqrtm(sigma1.dot(sigma2))

    # Handle numerical issues with complex numbers
    if np.iscomplexobj(covmean):
        covmean = covmean.real

    # Calculate the final FID score
    fid = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean)
    return fid

# Define the gradient penalty function
def gradient_penalty(discriminator, real_images, fake_images):
  # Dynamically adjust the alpha to match the batch size of real_image
  batch_size = tf.shape(real_images)[0]
  alpha = tf.random.uniform([batch_size, 1, 1, 1], 0.0, 1.0)

  # Explicitly reshape fake_images to match real_images
  fake_images = tf.reshape(fake_images, tf.shape(real_images))

  # Compute interpolated images
  interpolated = alpha * real_images + (1 - alpha) * fake_images

  with tf.GradientTape() as tape:
    tape.watch(interpolated)
    pred = discriminator(interpolated)

  grads = tape.gradient(pred, [interpolated])[0]
  norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=[1, 2, 3]))
  penalty = tf.reduce_mean((norm - 1.0) ** 2)
  return penalty

# Define the training loop with loss tracking
generator = build_generator()
discriminator = build_discriminator()

generator_optimizer = tf.keras.optimizers.Adam(learning_rate=1e-4, beta_1=0.5, beta_2=0.9)
discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5, beta_1=0.5, beta_2=0.9, clipnorm=1.0)

EPOCHS = 100 ##CHANGE##

# Define the number of disciminator steps per generator step
n_critic = 3 # Initial value
increase_n_critic = -30 # Threshold for discriminator loss
decrease_n_critic = -15 # Threshold for generator loss

# Lists to track losses
gen_losses = []
disc_losses = []

# Define the training step
def train_step(images, update_discriminator=True, update_generator=True):

  # Dynamically set batch size to match &apos;images&apos;
  batch_size = tf.shape(images)[0]
  noise = tf.random.normal([batch_size, noise_dim], mean = 0.0, stddev=1.5) # Increase noise variance

  with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
    generated_images = generator(noise, training=True)
    real_output = discriminator(images, training=True)
    fake_output = discriminator(generated_images, training=True)

    # Apply label smoothings
    real_labels = tf.ones_like(real_output) * 0.9 # Label smoothing
    fake_labels = tf.zeros_like(fake_output)

    # Generator loss
    gen_loss = -tf.reduce_mean(fake_output)
    disc_loss = -tf.reduce_mean(real_output) + tf.reduce_mean(fake_output)

    # Add gradient penalty to discriminator loss
    penalty = gradient_penalty(discriminator, images, generated_images)
    disc_loss += 5.0 * penalty # Adjust lambda as needed

  # Apply gradients conditionally
  if update_discriminator:
    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))

  if update_generator:
    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))

  # Print losses for each batch
  print(f&quot;Batch Generator Loss: {gen_loss.numpy()}, Batch Discriminator Loss: {disc_loss.numpy()}&quot;)

  return gen_loss, disc_loss

# Define the main training loop
def train(dataset, epochs):
  for epoch in range(epochs):
    epoch_gen_loss = 0.0
    epoch_disc_loss = 0.0
    batch_count = 0

    for image_batch in dataset:
      # Update the discriminator &apos;n_critic&apos; times
      for _ in range(n_critic):
        disc_loss, _ = train_step(image_batch, update_discriminator=True, update_generator=False)
        disc_losses.append(disc_loss.numpy())  # Append discriminator loss to list
        epoch_disc_loss += disc_loss.numpy()

      # Update the generator once after &apos;n_critic&apos; discriminator updates
      gen_loss, disc_loss = train_step(image_batch)
      gen_losses.append(gen_loss.numpy())  # Append generator loss to list
      disc_losses.append(disc_loss.numpy())  # Append discriminator loss to list

      epoch_gen_loss += gen_loss.numpy()
      epoch_disc_loss += disc_loss.numpy()
      batch_count += 1

    # Calculate average losses for the epoch
    avg_gen_loss = epoch_gen_loss / batch_count
    avg_disc_loss = epoch_disc_loss / batch_count

    print(f&quot;Epoch {epoch + 1}/{epochs} completed&quot;)
    print(f&quot;Epoch {epoch + 1}/{epochs} - Average Generator Loss: {avg_gen_loss}, Average Discriminator Loss: {avg_disc_loss}&quot;)

  # FID calculation at the end
  real_images = next(iter(dataset))
  noise = tf.random.normal([BATCH_SIZE, noise_dim])
  generated_images = generator(noise, training=False)
  fid_score = calculate_fid(real_images[:BATCH_SIZE], generated_images)
  print(f&quot;Final FID: {fid_score}&quot;)

# Train the model
train(train_dataset, EPOCHS)

# Plot the generator and discriminator losses

def plot_losses(gen_losses, disc_losses):
    plt.figure(figsize=(10, 5))
    plt.plot(gen_losses, label=&quot;Generator Loss&quot;)
    plt.plot(disc_losses, label=&quot;Discriminator Loss&quot;)
    plt.xlabel(&quot;Iterations&quot;)
    plt.ylabel(&quot;Loss&quot;)
    plt.legend()
    plt.title(&quot;Generator and Discriminator Losses over Training&quot;)
    plt.show()

# Plot the loss curves after training
plot_losses(gen_losses, disc_losses)

# Display a sample of real images
def show_real_images(dataset, num_images=16):
    real_images = next(iter(dataset))[:num_images]  # Take a batch of images
    real_images = (real_images + 1) / 2.0  # Rescale to [0, 1] for display

    plt.figure(figsize=(8, 8))
    for i in range(num_images):
        plt.subplot(4, 4, i + 1)
        plt.imshow(real_images[i])
        plt.axis(&quot;off&quot;)
    plt.suptitle(&quot;Sample of Real Images&quot;, fontsize=16)
    plt.show()

show_real_images(train_dataset)

# Display a sample of generated images
def generate_and_show_images(generator, noise_dim, num_images=16):
    noise = tf.random.normal([num_images, noise_dim])
    generated_images = generator(noise, training=False)
    generated_images = (generated_images + 1) / 2.0  # Rescale to [0, 1] for display

    plt.figure(figsize=(8, 8))
    for i in range(num_images):
        plt.subplot(4, 4, i + 1)
        plt.imshow(generated_images[i])
        plt.axis(&quot;off&quot;)
    plt.suptitle(&quot;Generated Images&quot;, fontsize=16)
    plt.show()

generate_and_show_images(generator, noise_dim)
    &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;stable-diffusion-model-code&quot;&gt;Stable Diffusion Model Code&lt;/h3&gt;

&lt;div class=&quot;code-viewer&quot;&gt;
    &lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;
    # -*- coding: utf-8 -*-
&quot;&quot;&quot;SDM_11_2024.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1hP-xCMK9nDsqSTad1XsiStW3zePndWCM
&quot;&quot;&quot;

# Load the EuroSAT dataset from Google Drive
from google.colab import drive
import tensorflow as tf

# Mount Google Drive
drive.mount(&apos;/content/drive&apos;)
# Set the dataset path
data_dir = &apos;/content/drive/MyDrive/EuroSAT/Forest&apos;

IMG_SIZE = 256 # Size for stable diffusion
BATCH_SIZE = 1 # Process one image at a time for generation

# Load EuroSAT dataset
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    label_mode=None,
    image_size=(IMG_SIZE, IMG_SIZE),
    batch_size=BATCH_SIZE
)

# Normalize images for compatibility with stable diffusion
train_dataset = train_dataset.map(lambda x: (x / 127.5) - 1)
train_dataset = train_dataset.prefetch(buffer_size=tf.data.AUTOTUNE)

# Load and configure the stable diffusion model
# Initialize the stable diffusion image-to-image pipeline
from diffusers import StableDiffusionImg2ImgPipeline
import torch

# Load stable diffusion image-to-image pipeline
pipe = StableDiffusionImg2ImgPipeline.from_pretrained(&apos;CompVis/stable-diffusion-v1-4&apos;, torch_dtype=torch.float16)

# Set the model to use the GPU
pipe = pipe.to(&apos;cuda&apos;) # This moves the model to the A100 GPU in Google Colab
print(&apos;Using GPU:&apos;, torch.cuda.get_device_name(0))

# Optionally disable the safety checker
pipe.safety_checker = None # Disable safety checker

# Generate and display original and generated images
import numpy as np
from PIL import Image

# Function to generate an image using stable diffusion
def generate_image(original_image, strength=0.02, guidance_scale=2):
    prompt = &quot;image&quot;  # Neutral prompt to minimize changes
    original_image_pil = Image.fromarray((original_image * 255).astype(np.uint8))
    generated_image_pil = pipe(prompt=prompt, image=original_image_pil, strength=strength, guidance_scale=guidance_scale).images[0]
    return generated_image_pil

# Generate and store images
generated_images = []
original_images = []

for original_images_batch in train_dataset.take(16):  # Take 16 images from the dataset
    original_image = original_images_batch[0].numpy()
    generated_image = generate_image(original_image)

    # Store the original and generated images
    original_images.append(original_image)
    generated_images.append(np.array(generated_image))

# Convert images to arrays for easy display
original_images = [(img + 1) / 2 for img in original_images]  # Rescale to [0, 1] for display
generated_images = [img / 255.0 for img in generated_images]  # Ensure [0, 1] range for generated images

# Display original and generated images
import matplotlib.pyplot as plt

# Plotting 16 images in a 4x8 grid for both original and generated images
fig, axes = plt.subplots(4, 8, figsize=(16, 8))

for i in range(16):
    # Original images on the left side (first 4 columns)
    axes[i // 4, (i % 4) * 2].imshow(original_images[i])
    axes[i // 4, (i % 4) * 2].axis(&quot;off&quot;)
    axes[i // 4, (i % 4) * 2].set_title(&quot;Original&quot;)

    # Generated images on the right side (next 4 columns)
    axes[i // 4, (i % 4) * 2 + 1].imshow(generated_images[i])
    axes[i // 4, (i % 4) * 2 + 1].axis(&quot;off&quot;)
    axes[i // 4, (i % 4) * 2 + 1].set_title(&quot;Generated&quot;)

plt.tight_layout()
plt.show()

# Calculate Frechet Inception Distance (FID)
from scipy.linalg import sqrtm

# Convert images to [0, 255] range for FID calculation
original_images_np = np.array([(img + 1) / 2 * 255.0 for img in original_images])  # Scale to [0, 255]
generated_images_np = np.array([img * 255.0 for img in generated_images])      # Scale to [0, 255]

# Load pre-trained InceptionV3 model for feature extraction
inception_model = tf.keras.applications.InceptionV3(include_top=False, pooling=&apos;avg&apos;, input_shape=(299, 299, 3))

# Function to preprocess images for InceptionV3
def preprocess_images(images):
    images = tf.image.resize(images, (299, 299))  # Resize to 299x299
    images = (images - 127.5) / 127.5  # Scale to [-1, 1]
    return images

# Function to calculate activations
def get_activations(images):
    images = preprocess_images(images)
    return inception_model.predict(images)

# Function to calculate the FID score
def calculate_fid(real_images, generated_images):
    act_real = get_activations(real_images)
    act_gen = get_activations(generated_images)

    # Calculate the mean and covariance of the activations
    mu_real, sigma_real = np.mean(act_real, axis=0), np.cov(act_real, rowvar=False)
    mu_gen, sigma_gen = np.mean(act_gen, axis=0), np.cov(act_gen, rowvar=False)

    # Calculate the difference in means
    mean_diff = np.sum((mu_real - mu_gen) ** 2)

    # Calculate the product of the covariances
    covmean, _ = sqrtm(sigma_real.dot(sigma_gen), disp=False)

    # Check for imaginary values in covmean
    if np.iscomplexobj(covmean):
        covmean = covmean.real

    # Calculate FID
    fid = mean_diff + np.trace(sigma_real + sigma_gen - 2 * covmean)
    return fid

# Calculate FID Score
fid_score = calculate_fid(original_images_np, generated_images_np)
print(&quot;FID Score:&quot;, fid_score)
    &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;fid-calculation-code&quot;&gt;FID Calculation Code&lt;/h3&gt;

&lt;div class=&quot;code-viewer&quot;&gt;
    &lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;
    # -*- coding: utf-8 -*-
&quot;&quot;&quot;FID s-score.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1mIyIUtYqWvQLyiQoxTWNZMBiUvFw8XeS
&quot;&quot;&quot;

import matplotlib.pyplot as plt

# Example FID scores
fid_gan = 1846.365750809347
fid_sd = 165.73935229494703

# Compute s-values
s_difference = fid_gan - fid_sd
s_ratio = fid_gan / fid_sd

# Print Results
print(f&quot;FID (GAN): {fid_gan}&quot;)
print(f&quot;FID (Stable Diffusion): {fid_sd}&quot;)
print(f&quot;s-value (Difference): {s_difference}&quot;)
print(f&quot;s-value (Ratio): {s_ratio}&quot;)

# Plot Results
models = [&apos;GAN&apos;, &apos;Stable Diffusion&apos;]
fid_scores = [fid_gan, fid_sd]

plt.bar(models, fid_scores, color=[&apos;blue&apos;, &apos;green&apos;])
plt.ylabel(&apos;FID Score&apos;)
plt.title(&apos;FID Scores Comparison&apos;)
plt.show()
    &lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;note&quot;&gt;Note&lt;/h3&gt;

&lt;p&gt;Sample images used in this project are sourced from the &lt;a href=&quot;https://github.com/phelber/eurosat&quot;&gt;EuroSAT Dataset&lt;/a&gt;.&lt;/p&gt;
</description>
        <pubDate>Tue, 26 Nov 2024 00:00:00 +0000</pubDate>
        <link>https://sagewoodard.github.io/gan-vs-sdm</link>
        <guid isPermaLink="true">https://sagewoodard.github.io/gan-vs-sdm</guid>
        
        <category>GAN</category>
        
        <category>Stable Diffusion</category>
        
        <category>Satellite Imagery</category>
        
        <category>Python</category>
        
        
        <category>Projects</category>
        
        <category>Machine Learning</category>
        
      </item>
    
  </channel>
</rss>