Spaces:
Runtime error
Runtime error
Create train.py
Browse files
train.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tensorflow as tf
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
import os
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
def load_dataset(dataset_path, image_size=(512, 512)):
|
| 8 |
+
images = []
|
| 9 |
+
for file in tqdm(os.listdir(dataset_path)):
|
| 10 |
+
img_path = os.path.join(dataset_path, file)
|
| 11 |
+
img = cv2.imread(img_path)
|
| 12 |
+
img = cv2.resize(img, image_size)
|
| 13 |
+
img = (img / 127.5) - 1.0 # Normalize
|
| 14 |
+
images.append(img)
|
| 15 |
+
return np.array(images)
|
| 16 |
+
|
| 17 |
+
def build_generator():
|
| 18 |
+
inputs = tf.keras.layers.Input(shape=(512, 512, 3))
|
| 19 |
+
x = tf.keras.layers.Conv2D(64, (7, 7), padding="same", activation="relu")(inputs)
|
| 20 |
+
x = tf.keras.layers.Conv2D(128, (3, 3), strides=2, padding="same")(x)
|
| 21 |
+
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
|
| 22 |
+
x = tf.keras.layers.Conv2DTranspose(64, (3, 3), strides=2, padding="same")(x)
|
| 23 |
+
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
|
| 24 |
+
x = tf.keras.layers.Conv2D(3, (7, 7), activation="tanh", padding="same")(x)
|
| 25 |
+
return tf.keras.models.Model(inputs, x)
|
| 26 |
+
|
| 27 |
+
def train_animegan(dataset_path, epochs=100, batch_size=8):
|
| 28 |
+
dataset = load_dataset(dataset_path)
|
| 29 |
+
generator = build_generator()
|
| 30 |
+
generator.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0002, beta_1=0.5), loss="mse")
|
| 31 |
+
for epoch in range(epochs):
|
| 32 |
+
for i in range(0, len(dataset), batch_size):
|
| 33 |
+
batch_images = dataset[i:i+batch_size]
|
| 34 |
+
noise = np.random.normal(0, 1, (batch_size, 512, 512, 3))
|
| 35 |
+
generator.train_on_batch(noise, batch_images)
|
| 36 |
+
print(f"Epoch {epoch+1}/{epochs} completed")
|
| 37 |
+
generator.save("AnimeGANv2_Hayao.h5")
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
train_animegan("path/to/dataset")
|
| 41 |
+
|