This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def main(): | |
from time import time | |
epochs = 600 | |
batches = 10 | |
generator = Generator(1) | |
discriminator = Discriminator(1, [64, 32, 1]) | |
noise_fn = lambda x: torch.rand((x, 1), device='cpu') | |
data_fn = lambda x: torch.randn((x, 1), device='cpu') | |
gan = VanillaGAN(generator, discriminator, noise_fn, data_fn, device='cpu') | |
loss_g, loss_d_real, loss_d_fake = [], [], [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class VanillaGAN(): | |
def __init__(self, generator, discriminator, noise_fn, data_fn, | |
batch_size=32, device='cpu', lr_d=1e-3, lr_g=2e-4): | |
"""A GAN class for holding and training a generator and discriminator | |
Args: | |
generator: a Ganerator network | |
discriminator: A Discriminator network | |
noise_fn: function f(num: int) -> pytorch tensor, (latent vectors) | |
data_fn: function f(num: int) -> pytorch tensor, (real samples) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Discriminator(nn.Module): | |
def __init__(self, input_dim, layers): | |
"""A discriminator for discerning real from generated samples. | |
params: | |
input_dim (int): width of the input | |
layers (List[int]): A list of layer widths including output width | |
Output activation is Sigmoid. | |
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Generator(nn.Module): | |
def __init__(self, latent_dim, output_activation=None): | |
"""A generator for mapping a latent space to a sample space. | |
Args: | |
latent_dim (int): latent dimension ("noise vector") | |
layers (List[int]): A list of layer widths including output width | |
output_activation: torch activation function or None | |
""" | |
super(Generator, self).__init__() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from tensorflow.keras.layers import Input, Dense, BatchNormalization, Activation, LeakyReLU | |
from tensorflow.keras.models import Model | |
from tensorflow.keras.optimizers import Adam | |
import tensorflow as tf | |
import matplotlib.pyplot as plt | |
def build_G(batchnorm_momentum=0.9): | |
input_layer = Input(shape=(2,)) | |
for i in range(4): |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Set up the environment and collect the observation space and action space sizes | |
env = gym.make("CartPole-v1") | |
observation_space = env.observation_space.shape[0] | |
action_space = env.action_space.n | |
# The function for creating the initial population | |
organism_creator = lambda : Organism([observation_space, 16, 16, 16, action_space], output='softmax') | |
def simulate_and_evaluate(organism, trials=1): | |
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load the data | |
df = pd.read_csv('iris.csv') | |
# Enumerate the classes | |
unique_classes = sorted(list(set(df['variety']))) | |
class_number = {y : x for x,y in enumerate(unique_classes)} | |
df['variety'] = [class_number[x] for x in df['variety']] | |
# Convert to numpy array and standardize the features | |
data_X = df[['sepal.length', 'sepal.width', 'petal.length', 'petal.width']].values | |
data_Y = df[['variety']].values | |
data_X = data_X - np.min(data_X, axis=0) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The function to create the initial population | |
organism_creator = lambda : Organism([1, 16, 16, 16, 1], output='linear') | |
# The function we are trying to learn. numpy doesn't have tau... | |
true_function = lambda x : np.sin(2 * np.pi * x) # | |
# The loss function, mean squared error, will serve as the negative fitness | |
loss_function = lambda y_true, y_estimate : np.mean((y_true - y_estimate)**2) | |
def simulate_and_evaluate(organism, replicates=1): | |
""" | |
Randomly generate `replicates` samples in [0,1], |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
import numpy as np | |
class Organism(): | |
def __init__(self, dimensions, use_bias=True, output='softmax'): | |
self.layers = [] | |
self.biases = [] | |
self.use_bias = use_bias | |
self.output = self._activation(output) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Organism(): | |
# [Some code removed here] | |
def mutate(self, stdev=0.03): | |
for i in range(len(self.layers)): | |
self.layers[i] += np.random.normal(0, stdev, self.layers[i].shape) | |
if self.use_bias: | |
self.biases[i] += np.random.normal(0, stdev, self.biases[i].shape) |
NewerOlder