SkillForge45 commited on
Commit
4bac1af
·
verified ·
1 Parent(s): 8047532

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +79 -0
model.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import tensorflow as tf
3
+ import matplotlib.pyplot as plt
4
+
5
+ # Parameters
6
+ IMG_SIZE = 64
7
+ LATENT_DIM = 128 # Dimension of the input noise
8
+ BATCH_SIZE = 1
9
+
10
+ # Generator (turns noise into an image)
11
+ def build_generator():
12
+ model = tf.keras.Sequential([
13
+ tf.keras.layers.Dense(8 * 8 * 64, activation='relu', input_dim=LATENT_DIM),
14
+ tf.keras.layers.Reshape((8, 8, 64)),
15
+ tf.keras.layers.Conv2DTranspose(64, (4,4), strides=2, padding='same', activation='relu'),
16
+ tf.keras.layers.Conv2DTranspose(32, (4,4), strides=2, padding='same', activation='relu'),
17
+ tf.keras.layers.Conv2DTranspose(3, (4,4), strides=2, padding='same', activation='sigmoid') # RGB [0,1]
18
+ ])
19
+ return model
20
+
21
+ # Discriminator (evaluates how "interesting" an image is)
22
+ def build_discriminator():
23
+ model = tf.keras.Sequential([
24
+ tf.keras.layers.Conv2D(32, (3,3), strides=2, padding='same', input_shape=(IMG_SIZE, IMG_SIZE, 3)),
25
+ tf.keras.layers.LeakyReLU(0.2),
26
+ tf.keras.layers.Conv2D(64, (3,3), strides=2, padding='same'),
27
+ tf.keras.layers.LeakyReLU(0.2),
28
+ tf.keras.layers.Flatten(),
29
+ tf.keras.layers.Dense(1, activation='sigmoid') # "How cool is this?"
30
+ ])
31
+ return model
32
+
33
+ # Create models
34
+ generator = build_generator()
35
+ discriminator = build_discriminator()
36
+
37
+ # Loss function and optimizers
38
+ cross_entropy = tf.keras.losses.BinaryCrossentropy()
39
+ g_optimizer = tf.keras.optimizers.Adam(0.0002, beta_1=0.5)
40
+ d_optimizer = tf.keras.optimizers.Adam(0.0002, beta_1=0.5)
41
+
42
+ # Training function
43
+ @tf.function
44
+ def train_step():
45
+ # 1. Generate random noise
46
+ noise = tf.random.normal([BATCH_SIZE, LATENT_DIM])
47
+
48
+ # 2. Train discriminator on "good" data (but we don't have any → just learn to distinguish noise)
49
+ with tf.GradientTape() as d_tape:
50
+ generated_images = generator(noise, training=True)
51
+ real_output = discriminator(tf.random.uniform((BATCH_SIZE, IMG_SIZE, IMG_SIZE, 3)), training=True) # fake "real" data
52
+ fake_output = discriminator(generated_images, training=True)
53
+ d_loss = cross_entropy(tf.ones_like(fake_output), fake_output) # force it to think generated images are "real"
54
+
55
+ d_gradients = d_tape.gradient(d_loss, discriminator.trainable_variables)
56
+ d_optimizer.apply_gradients(zip(d_gradients, discriminator.trainable_variables))
57
+
58
+ # 3. Train generator
59
+ with tf.GradientTape() as g_tape:
60
+ generated_images = generator(noise, training=True)
61
+ fake_output = discriminator(generated_images, training=True)
62
+ g_loss = cross_entropy(tf.ones_like(fake_output), fake_output) # goal is to fool the discriminator
63
+
64
+ g_gradients = g_tape.gradient(g_loss, generator.trainable_variables)
65
+ g_optimizer.apply_gradients(zip(g_gradients, generator.trainable_variables))
66
+
67
+ return d_loss, g_loss
68
+
69
+ # Mini-training (50 steps)
70
+ for epoch in range(50):
71
+ d_loss, g_loss = train_step()
72
+ if epoch % 10 == 0:
73
+ print(f"Epoch {epoch}, D Loss: {d_loss:.3f}, G Loss: {g_loss:.3f}")
74
+ # Generate sample image
75
+ test_noise = tf.random.normal([1, LATENT_DIM])
76
+ generated_img = generator(test_noise, training=False)[0]
77
+ plt.imshow(generated_img)
78
+ plt.axis('off')
79
+ plt.show()