├── Stackelberg GAN ├── images │ ├── exp1.png │ ├── exp2.png │ ├── exp3.png │ ├── mnist.png │ ├── converge.gif │ ├── architecture.png │ ├── fashion_mnist.png │ └── cifar10_imagenet.png ├── CIFAR-10 │ ├── utils.py │ ├── ops.py │ ├── main.py │ └── models.py ├── Gaussian mixture │ ├── gan_branch_mG.py │ └── gan_stackelberg_mG.py ├── fashion_MNIST │ └── gan_mnist_fashion_classifier.py └── MNIST │ └── gan_mnist_classifier.py ├── README.md └── LICENSE /Stackelberg GAN/images/exp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/exp1.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/exp2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/exp2.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/exp3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/exp3.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/mnist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/mnist.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/converge.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/converge.gif -------------------------------------------------------------------------------- /Stackelberg GAN/images/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/architecture.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/fashion_mnist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/fashion_mnist.png -------------------------------------------------------------------------------- /Stackelberg GAN/images/cifar10_imagenet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongyanz/Stackelberg-GAN/HEAD/Stackelberg GAN/images/cifar10_imagenet.png -------------------------------------------------------------------------------- /Stackelberg GAN/CIFAR-10/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import numpy as np 6 | import math 7 | import matplotlib 8 | matplotlib.use('TkAgg') 9 | import matplotlib.pyplot as plt 10 | plt.switch_backend('agg') 11 | plt.style.use('ggplot') 12 | 13 | class Prior(object): 14 | def __init__(self, type): 15 | self.type = type 16 | 17 | def sample(self, shape): 18 | if self.type == "uniform": 19 | return np.random.uniform(-1.0, 1.0, shape) 20 | else: 21 | return np.random.normal(0, 1, shape) 22 | 23 | def conv_out_size_same(size, stride): 24 | return int(math.ceil(float(size) / float(stride))) 25 | 26 | def make_batches(size, batch_size): 27 | '''Returns a list of batch indices (tuples of indices). 28 | ''' 29 | return [(i, min(size, i + batch_size)) for i in range(0, size, batch_size)] 30 | 31 | def create_image_grid(x, img_size, tile_shape): 32 | assert (x.shape[0] == tile_shape[0] * tile_shape[1]) 33 | assert (x[0].shape == img_size) 34 | 35 | img = np.zeros((img_size[0] * tile_shape[0] + tile_shape[0] - 1, 36 | img_size[1] * tile_shape[1] + tile_shape[1] - 1, 37 | 3)) 38 | 39 | for t in range(x.shape[0]): 40 | i, j = t // tile_shape[1], t % tile_shape[1] 41 | img[i * img_size[0] + i : (i + 1) * img_size[0] + i, j * img_size[1] + j : (j + 1) * img_size[1] + j] = x[t] 42 | 43 | return img 44 | 45 | def merge(images, size): 46 | h, w = images.shape[1], images.shape[2] 47 | img = np.zeros((h * size[0], w * size[1], 3)) 48 | 49 | for idx, image in enumerate(images): 50 | i = idx % size[1] 51 | j = idx // size[1] 52 | img[j*h:j*h+h, i*w:i*w+w, :] = image 53 | 54 | return img 55 | 56 | def disp_scatter(x, g, gen, num_gens, fig=None, ax=None): 57 | colors = ['darkblue', 'yellow', 'indigo', 'darkgreen', 'purple', 58 | 'dodgerblue', 'lime', 'brown', 'darkcyan', 'deeppink'] 59 | 60 | if ax is None: 61 | fig, ax = plt.subplots() 62 | 63 | ax.cla() 64 | ax.scatter(x[:, 0], x[:, 1], s=10, marker='+', color='r', alpha=0.8) 65 | for i in range(num_gens): 66 | ax.scatter(g[gen == i, 0], g[gen == i, 1], s=10, marker='o', 67 | color=colors[i], alpha=0.8) 68 | ax.legend(["real data"] + ['gen {}'.format(i) for i in range(num_gens)]) 69 | ax.set_xlim(-3, 3) 70 | ax.set_ylim(-3, 3) 71 | return fig, ax -------------------------------------------------------------------------------- /Stackelberg GAN/CIFAR-10/ops.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import numpy as np 6 | import tensorflow as tf 7 | 8 | def lrelu(x, alpha=0.2): 9 | return tf.maximum(x, alpha * x) 10 | 11 | def linear(input, output_dim, scope='linear', stddev=0.01): 12 | norm = tf.random_normal_initializer(stddev=stddev) 13 | const = tf.constant_initializer(0.0) 14 | with tf.variable_scope(scope): 15 | w = tf.get_variable('weights', [input.get_shape()[1], output_dim], initializer=norm) 16 | b = tf.get_variable('biases', [output_dim], initializer=const) 17 | return tf.matmul(input, w) + b 18 | 19 | def conv2d(input_, output_dim, 20 | k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, 21 | name="conv2d"): 22 | with tf.variable_scope(name): 23 | w = tf.get_variable('weights', [k_h, k_w, input_.get_shape()[-1], output_dim], 24 | initializer=tf.truncated_normal_initializer(stddev=stddev)) 25 | conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME') 26 | 27 | biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0)) 28 | # conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape()) 29 | 30 | return tf.nn.bias_add(conv, biases) 31 | 32 | 33 | def deconv2d(input_, output_shape, 34 | k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, 35 | name="deconv2d", with_w=False): 36 | with tf.variable_scope(name): 37 | # filter : [height, width, output_channels, in_channels] 38 | w = tf.get_variable('weights', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], 39 | initializer=tf.random_normal_initializer(stddev=stddev)) 40 | 41 | try: 42 | deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape, 43 | strides=[1, d_h, d_w, 1]) 44 | 45 | # Support for versions of TensorFlow before 0.7.0 46 | except AttributeError: 47 | deconv = tf.nn.deconv2d(input_, w, output_shape=output_shape, 48 | strides=[1, d_h, d_w, 1]) 49 | 50 | biases = tf.get_variable('biases', [output_shape[-1]], 51 | initializer=tf.constant_initializer(0.0)) 52 | deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) 53 | 54 | if with_w: 55 | return deconv, w, biases 56 | else: 57 | return deconv 58 | 59 | def gmm_sample(num_samples, mix_coeffs, mean, cov): 60 | z = np.random.multinomial(num_samples, mix_coeffs) 61 | samples = np.zeros(shape=[num_samples, len(mean[0])]) 62 | i_start = 0 63 | for i in range(len(mix_coeffs)): 64 | i_end = i_start + z[i] 65 | samples[i_start:i_end, :] = np.random.multivariate_normal( 66 | mean=np.array(mean)[i, :], 67 | cov=np.diag(np.array(cov)[i, :]), 68 | size=z[i]) 69 | i_start = i_end 70 | return samples 71 | -------------------------------------------------------------------------------- /Stackelberg GAN/CIFAR-10/main.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | 5 | import sys 6 | import pickle 7 | import argparse 8 | import numpy as np 9 | import tensorflow as tf 10 | import os 11 | from models import SGAN 12 | 13 | 14 | FLAGS = None 15 | # os.environ['CUDA_VISIBLE_DEVICES'] = '0' 16 | 17 | def main(_): 18 | tmp = pickle.load(open("data/cifar10_train.pkl", "rb")) 19 | x_train = tmp['data'].astype(np.float32).reshape([-1, 32, 32, 3]) / 127.5 - 1. 20 | print(x_train.shape) 21 | model = SGAN( 22 | num_z=FLAGS.num_z, 23 | beta=FLAGS.beta, 24 | num_gens=FLAGS.num_gens, 25 | d_batch_size=FLAGS.d_batch_size, 26 | g_batch_size=FLAGS.g_batch_size, 27 | z_prior=FLAGS.z_prior, 28 | learning_rate1=FLAGS.learning_rate1, 29 | learning_rate2=FLAGS.learning_rate2, 30 | img_size=(32, 32, 3), 31 | g_num_conv_layers=FLAGS.g_num_conv_layers, 32 | d_num_conv_layers=FLAGS.d_num_conv_layers, 33 | num_gen_feature_maps=FLAGS.num_gen_feature_maps, 34 | num_dis_feature_maps=FLAGS.num_dis_feature_maps, 35 | num_epochs=FLAGS.num_epochs, 36 | sample_fp="classifier_samples_g"+str(FLAGS.num_gens)+"_epoch_"+str(FLAGS.num_epochs)+"_layers_"+str(FLAGS.g_num_conv_layers)+"_lr1_"+str(FLAGS.learning_rate1)+"_lr2_"+str(FLAGS.learning_rate2)+"/samples_{epoch:04d}.png", 37 | sample_by_gen_fp="classifier_samples_by_gen_g"+str(FLAGS.num_gens)+"_epoch_"+str(FLAGS.num_epochs)+"_layers_"+str(FLAGS.g_num_conv_layers)+"_lr1_"+str(FLAGS.learning_rate1)+"_lr2_"+str(FLAGS.learning_rate2)+"_new", 38 | random_seed=6789, 39 | checkpoint_dir="classifier_checkpoint_g"+str(FLAGS.num_gens)+"_best") 40 | model.fit(x_train) 41 | # model.predict() 42 | 43 | 44 | if __name__ == '__main__': 45 | parser = argparse.ArgumentParser() 46 | parser.add_argument('--num_z', type=int, default=100, 47 | help='Number of latent units.') 48 | parser.add_argument('--beta', type=float, default=0.1, 49 | help='Diversity parameter beta.') 50 | parser.add_argument('--num_gens', type=int, default=10, 51 | help='Number of generators.') 52 | parser.add_argument('--d_batch_size', type=int, default=64, 53 | help='Minibatch size for the discriminator.') 54 | parser.add_argument('--g_batch_size', type=int, default=64, 55 | help='Minibatch size for the generators.') 56 | parser.add_argument('--z_prior', type=str, default="uniform", 57 | help='Prior distribution of the noise (uniform/gaussian).') 58 | parser.add_argument('--learning_rate1', type=float, default=0.000005, 59 | help='Learning rate1.') 60 | parser.add_argument('--learning_rate2', type=float, default=0.00001, 61 | help='Learning rate2.') 62 | parser.add_argument('--g_num_conv_layers', type=int, default=2, 63 | help='Number of G convolutional layers.') 64 | parser.add_argument('--d_num_conv_layers', type=int, default=3, 65 | help='Number of D convolutional layers.') 66 | parser.add_argument('--num_gen_feature_maps', type=int, default=128, 67 | help='Number of feature maps of Generator.') 68 | parser.add_argument('--num_dis_feature_maps', type=int, default=128, 69 | help='Number of feature maps of Discriminator.') 70 | parser.add_argument('--num_epochs', type=int, default=500, 71 | help='Number of epochs.') 72 | FLAGS, unparsed = parser.parse_known_args() 73 | tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stackelberg-GAN 2 | This is the code for [the paper](https://arxiv.org/abs/1811.08010) "Stackelberg GAN: Towards Provable Minimax Equilibrium via Multi-Generator Architectures". 3 | 4 | ## Install 5 | This code depends on python 3.6, pytorch 0.4.1 (for the experiemnts of mixture of Gaussians, MNIST, and Fashion MNIST) and Tensorflow (version>=1.4.1, for CIFAR-10 and Tiny Imagenet experiments). We suggest to install the dependencies using Anaconda or Miniconda. Here is an exemplary command: 6 | ``` 7 | $ wget https://repo.anaconda.com/archive/Anaconda3-5.1.0-Linux-x86_64.sh 8 | $ bash Anaconda3-5.1.0-Linux-x86_64.sh 9 | $ source ~/.bashrc 10 | $ conda install pytorch=0.4.1 11 | ``` 12 | 13 | ## Get started 14 | To get started, cd into the directory. Then runs the scripts: 15 | * gan_stackelberg_mG.py is a demo on the performance of Stackelberg GAN on Gaussian mixture dataset, 16 | * gan_branch_mG.py is a demo on the performance of multi-branch GAN (a baseline method) on Gaussian mixture dataset, 17 | * gan_mnist_classifier.py is a demo on the performance of Stackelberg GAN on MNIST dataset, 18 | * gan_mnist_fashion_classifier.py is a demo on the performance of Stackelberg GAN on fashion-MNIST dataset. 19 | * CIFAR-10: This folder contains code implementing the proposed Stackelberg GAN in CIFAR-10 using TensorFlow (version>=1.4.1). models.py constructed the model of Stackelberg GAN. main.py conducted experiment based on CIFAR-10 dataset. In main.py, model.fit() trains the Stackelberg GAN model based on the given dataset, while model.predict() outputs the generated examples. 20 | 21 | ## Using the code 22 | The command `python xxx.py --help` gives the help information about how to run the code. 23 | 24 | ## Architecture of Stackelberg GAN 25 | 26 | Stackelberg GAN is a general framework which can be built on top of all variants of standard GANs. The key idea is to apply multiple generators which team up to play against the discriminator. 27 | 28 |

29 | 30 |

31 | 32 | 33 | 34 | ## Experimental Results 35 | 36 | ### Mixture of Gaussians 37 | 38 |

39 | 40 |

41 | 42 | We test the performance of varying architectures of GANs on a synthetic mixture of Gaussians dataset with 8 modes and 0.01 standard deviation. We observe the following phenomena: 43 | 44 | *Naïvely increasing capacity of one-generator architecture does not alleviate mode collapse*. It shows 45 | that the multi-generator architecture in the Stackelberg GAN effectively alleviates the mode collapse issue. 46 | Though naïvely increasing capacity of one-generator architecture alleviates mode dropping issue, for more 47 | challenging mode collapse issue, the effect is not obvious. 48 | 49 | #### Running Example 50 |

51 | 52 |

53 | 54 | *Stackelberg GAN outperforms multi-branch models.* We compare performance of multi-branch GAN (i.e., classic GAN with multi-branch architecture for its generator) and Stackelberg GAN. The performance of Stackelberg GAN is also better than multi-branch GAN of much larger capacity. 55 | 56 | #### Running Example 57 |

58 | 59 |

60 | 61 | *Generators tend to learn balanced number of modes when they have same capacity*. We observe that 62 | for varying number of generators, each generator in the Stackelberg GAN tends to learn equal number of 63 | modes when the modes are symmetric and every generator has same capacity. 64 | 65 | #### Running Example 66 |

67 | 68 |

69 | 70 | ### MNIST Dataset 71 | The following figure shows the diversity of generated digits by Stackelberg GAN with varying number of generators. *Left Figure:* 72 | Digits generated by the standard GAN. It shows that the standard GAN generates many "1"’s which are not very diverse. *Middle Figure:* Digits generated by the Stackelberg GAN with 5 generators, where every two rows correspond to one generator. *Right Figure:* Digits generated by the Stackelberg GAN with 10 generators, where each row corresponds to one generator. As the number of generators increases, the images tend to be more diverse. 73 | 74 | #### Running Example 75 |

76 | 77 |

78 | 79 | ### Fashion-MNIST Dataset 80 | The following figure shows the diversity of generated fashions by Stackelberg GAN with varying number of generators. *Left Figure:* 81 | Examples generated by the standard GAN. It shows that the standard GAN fails to generate bags. *Middle Figure:* Examples generated by the Stackelberg GAN with 5 generators, where every two rows correspond to one generator. *Right Figure:* Examples generated by the Stackelberg GAN with 10 generators, where each row corresponds to one generator. 82 | 83 | #### Running Example 84 |

85 | 86 |

87 | 88 | ### CIFAR-10/Tiny ImageNet Dataset 89 | The following figure shows the examples generated by Stackelberg GAN with 10 generators on CIFAR-10 and Tiny ImageNet. *Left Figure:* 90 | Examples generated by the Stackelberg GAN on CIFAR-10. *Right Figure:* Examples generated by the Stackelberg GAN on ImageNet. 91 | 92 | #### Running Example 93 |

94 | 95 |

96 | 97 | 98 | 99 | ## Reference 100 | For technical details and full experimental results, see [the paper](https://arxiv.org/abs/1811.08010). 101 | ``` 102 | @article{Zhang2018stackelberg, 103 | author = {Hongyang Zhang and Susu Xu and Jiantao Jiao and Pengtao Xie and Ruslan Salakhutdinov and Eric P. Xing}, 104 | title = {Stackelberg GAN: Towards Provable Minimax Equilibrium via Multi-Generator Architectures}, 105 | journal={arXiv preprint arXiv:1811.08010}, 106 | year = {2018} 107 | } 108 | ``` 109 | 110 | ## Contact 111 | Please contact hongyanz@cs.cmu.edu if you have any question on the codes. 112 | -------------------------------------------------------------------------------- /Stackelberg GAN/Gaussian mixture/gan_branch_mG.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import numpy as np 4 | import math 5 | 6 | import torchvision.transforms as transforms 7 | from torchvision.utils import save_image 8 | 9 | from torch.utils.data import DataLoader 10 | from torchvision import datasets 11 | from torch.autograd import Variable 12 | 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | import torch 16 | import shutil 17 | 18 | import matplotlib.pyplot as plt 19 | plt.switch_backend('agg') 20 | import seaborn as sns 21 | import matplotlib 22 | 23 | os.makedirs('images_branch_mG', exist_ok=True) 24 | shutil.rmtree('images_branch_mG') 25 | os.makedirs('images_branch_mG', exist_ok=True) 26 | 27 | parser = argparse.ArgumentParser() 28 | parser.add_argument('--n_epochs', type=int, default=200, help='number of epochs of training') 29 | parser.add_argument('--batch_size', type=int, default=64, help='size of the batches') 30 | parser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate') 31 | parser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient') 32 | parser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient') 33 | parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation') 34 | parser.add_argument('--latent_dim', type=int, default=2, help='dimensionality of the latent space') 35 | parser.add_argument('--img_size', type=int, default=28, help='size of each image dimension') 36 | parser.add_argument('--channels', type=int, default=1, help='number of image channels') 37 | parser.add_argument('--sample_interval', type=int, default=400, help='interval betwen image samples') 38 | parser.add_argument('--n_paths_D', type=int, default=1, help='number of paths of discriminator') 39 | parser.add_argument('--n_paths_G', type=int, default=1, help='number of paths of generator') 40 | opt = parser.parse_args() 41 | print(opt) 42 | 43 | 44 | cuda = True if torch.cuda.is_available() else False 45 | 46 | class Generator(nn.Module): 47 | def __init__(self): 48 | super(Generator, self).__init__() 49 | 50 | def block(in_feat, out_feat, normalize=True): 51 | layers = [nn.Linear(in_feat, out_feat)] 52 | if normalize: 53 | layers.append(nn.BatchNorm1d(out_feat, 0.8)) 54 | layers.append(nn.LeakyReLU(0.2, inplace=True)) 55 | return layers 56 | 57 | modules = nn.ModuleList() 58 | for _ in range(opt.n_paths_G): 59 | modules.append(nn.Sequential( 60 | *block(opt.latent_dim, 128, normalize=False), 61 | *block(128, 256), 62 | *block(256, 512), 63 | *block(512, 1024), 64 | nn.Linear(1024, 2), 65 | nn.Tanh() 66 | )) 67 | self.paths = modules 68 | 69 | def forward(self, z): 70 | img = torch.zeros(z.shape[0], 2).cuda() 71 | for path in self.paths: 72 | img += path(z) 73 | img = img/opt.n_paths_G 74 | return img 75 | 76 | class Discriminator(nn.Module): 77 | def __init__(self): 78 | super(Discriminator, self).__init__() 79 | modules = nn.ModuleList() 80 | for _ in range(opt.n_paths_D): 81 | modules.append(nn.Sequential( 82 | nn.Linear(2, 512), 83 | nn.LeakyReLU(0.2, inplace=True), 84 | nn.Linear(512, 256), 85 | nn.LeakyReLU(0.2, inplace=True), 86 | nn.Linear(256, 1), 87 | nn.Sigmoid() 88 | )) 89 | self.paths = modules 90 | 91 | def forward(self, img): 92 | img_flat = img 93 | validity = [] 94 | for path in self.paths: 95 | validity.append(path(img_flat)) 96 | validity = torch.cat(validity, dim=1) 97 | return validity 98 | 99 | # Loss function 100 | adversarial_loss = torch.nn.BCELoss() 101 | 102 | # Initialize generator and discriminator 103 | generator = Generator() 104 | discriminator = Discriminator() 105 | 106 | if cuda: 107 | generator.cuda() 108 | discriminator.cuda() 109 | adversarial_loss.cuda() 110 | 111 | # Configure data loader 112 | n_mixture = 8 113 | radius = 1 114 | std = 0.01 115 | thetas = np.linspace(0, 2 * (1-1/n_mixture) * np.pi, n_mixture) 116 | xs, ys = radius * np.sin(thetas), radius * np.cos(thetas) 117 | data_size = 1000*n_mixture 118 | data = torch.zeros(data_size, 2) 119 | for i in range(data_size): 120 | coin = np.random.randint(0, n_mixture) 121 | data[i, :] = torch.normal(mean=torch.Tensor([xs[coin], ys[coin]]), std=std*torch.ones(1, 2)) 122 | 123 | 124 | # Optimizers 125 | optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 126 | optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 127 | 128 | Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor 129 | 130 | # ---------- 131 | # Training 132 | # ---------- 133 | n_batch = math.ceil(data_size/opt.batch_size) 134 | 135 | for epoch in range(opt.n_epochs): 136 | colors = matplotlib.cm.rainbow(np.linspace(0, 1, 1+opt.n_paths_G)) 137 | plt.plot(data[:, 0].cpu().numpy(), data[:, 1].cpu().numpy(), color=colors[0], marker='.', linestyle='None') 138 | z = Variable(Tensor(np.random.normal(0, 1, (8000//opt.n_paths_G, opt.latent_dim)))) 139 | for k in range(opt.n_paths_G): 140 | gen_data = generator.paths[k](z).detach() 141 | plt.plot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), color=colors[1+k], marker='.', linestyle='None') 142 | 143 | for i in range(n_batch): 144 | 145 | imgs = data[i*opt.batch_size:min((i+1)*opt.batch_size, data_size-1), :] 146 | 147 | # Adversarial ground truths 148 | valid = Variable(Tensor(imgs.size(0), opt.n_paths_D).fill_(1.0), requires_grad=False) 149 | fake = Variable(Tensor(imgs.size(0), opt.n_paths_D).fill_(0.0), requires_grad=False) 150 | 151 | # Configure input 152 | real_imgs = Variable(imgs.type(Tensor)) 153 | 154 | # ----------------- 155 | # Train Generator 156 | # ----------------- 157 | 158 | optimizer_G.zero_grad() 159 | 160 | # Sample noise as generator input 161 | z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) 162 | 163 | # Generate a batch of images 164 | gen_imgs = generator(z) 165 | 166 | # Loss measures generator's ability to fool the discriminator 167 | g_loss = adversarial_loss(discriminator(gen_imgs), valid) 168 | 169 | g_loss.backward() 170 | optimizer_G.step() 171 | 172 | # --------------------- 173 | # Train Discriminator 174 | # --------------------- 175 | 176 | optimizer_D.zero_grad() 177 | 178 | d_loss = 0 179 | real_loss = adversarial_loss(discriminator(real_imgs), valid) 180 | 181 | # Generate a batch of images 182 | gen_imgs = generator(z) 183 | 184 | # Measure discriminator's ability to classify real from generated samples 185 | fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake) 186 | d_loss = (real_loss + fake_loss) / 2 187 | 188 | d_loss.backward() 189 | optimizer_D.step() 190 | 191 | print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch+1, opt.n_epochs, i, n_batch, 192 | d_loss.item(), g_loss.item())) 193 | 194 | colors = matplotlib.cm.rainbow(np.linspace(0, 1, 1+opt.n_paths_G)) 195 | plt.plot(data[:, 0].cpu().numpy(), data[:, 1].cpu().numpy(), color=colors[0], marker='.', linestyle='None') 196 | 197 | z = Variable(Tensor(np.random.normal(0, 1, (8000//opt.n_paths_G, opt.latent_dim)))) 198 | temp = [] 199 | for k in range(opt.n_paths_G): 200 | # temp.append(generator.paths[k](z).detach()) 201 | # gen_data = torch.cat(temp, dim=0) 202 | # sns.jointplot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), kind='kde', stat_func=None) 203 | gen_data = generator.paths[k](z).detach() 204 | plt.plot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), color=colors[1+k], marker='.', linestyle='None') 205 | 206 | plt.savefig('images_branch_mG/%d.png' % epoch) 207 | plt.close('all') 208 | -------------------------------------------------------------------------------- /Stackelberg GAN/fashion_MNIST/gan_mnist_fashion_classifier.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import numpy as np 4 | import math 5 | 6 | import torchvision.transforms as transforms 7 | from torchvision.utils import save_image 8 | 9 | from torch.utils.data import DataLoader 10 | from torchvision import datasets 11 | from torch.autograd import Variable 12 | from tqdm import tqdm 13 | 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | import torch 17 | import shutil 18 | 19 | os.makedirs('images_ensemble_fashionmnist10', exist_ok=True) 20 | shutil.rmtree('images_ensemble_fashionmnist10') 21 | os.makedirs('images_ensemble_fashionmnist10', exist_ok=True) 22 | 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('--n_epochs', type=int, default=500, help='number of epochs of training') 25 | parser.add_argument('--batch_size', type=int, default=100, help='size of the batches') 26 | parser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate') 27 | parser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient') 28 | parser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient') 29 | parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation') 30 | parser.add_argument('--latent_dim', type=int, default=2, help='dimensionality of the latent space') 31 | parser.add_argument('--img_size', type=int, default=28, help='size of each image dimension') 32 | parser.add_argument('--channels', type=int, default=1, help='number of image channels') 33 | parser.add_argument('--sample_interval', type=int, default=400, help='interval betwen image samples') 34 | parser.add_argument('--n_paths_G', type=int, default=10, help='number of paths of generator') 35 | opt = parser.parse_args() 36 | print(opt) 37 | 38 | img_shape = (opt.channels, opt.img_size, opt.img_size) 39 | 40 | cuda = True if torch.cuda.is_available() else False 41 | 42 | class Generator(nn.Module): 43 | def __init__(self): 44 | super(Generator, self).__init__() 45 | 46 | def block(in_feat, out_feat, normalize=True): 47 | layers = [nn.Linear(in_feat, out_feat)] 48 | if normalize: 49 | layers.append(nn.BatchNorm1d(out_feat, 0.8)) 50 | layers.append(nn.LeakyReLU(0.2, inplace=True)) 51 | return layers 52 | 53 | modules = nn.ModuleList() 54 | for _ in range(opt.n_paths_G): 55 | modules.append(nn.Sequential( 56 | *block(opt.latent_dim, 128, normalize=False), 57 | *block(128, 256), 58 | *block(256, 512), 59 | *block(512, 1024), 60 | nn.Linear(1024, int(np.prod(img_shape))), 61 | nn.Tanh() 62 | )) 63 | self.paths = modules 64 | 65 | def forward(self, z): 66 | img = [] 67 | for path in self.paths: 68 | img.append(path(z).view(img.size(0), *img_shape)) 69 | img = torch.cat(img, dim=0) 70 | return img 71 | 72 | class Discriminator(nn.Module): 73 | def __init__(self): 74 | super(Discriminator, self).__init__() 75 | self.fc1 = nn.Linear(int(np.prod(img_shape)), 512) 76 | self.lr1 = nn.LeakyReLU(0.2, inplace=True) 77 | self.fc2 = nn.Linear(512, 256) 78 | self.lr2 = nn.LeakyReLU(0.2, inplace=True) 79 | modules = nn.ModuleList() 80 | modules.append(nn.Sequential( 81 | nn.Linear(256, 1), 82 | nn.Sigmoid(), 83 | )) 84 | modules.append(nn.Sequential( 85 | nn.Linear(256, 10), 86 | )) 87 | self.paths = modules 88 | 89 | def forward(self, img): 90 | img_flat = img.view(img.size(0), -1) 91 | img_flat = self.lr2(self.fc2(self.lr1(self.fc1(img_flat)))) 92 | validity = self.paths[0](img_flat) 93 | classifier = F.log_softmax(self.paths[1](img_flat), dim=1) 94 | return validity, classifier 95 | 96 | # Loss function 97 | adversarial_loss = torch.nn.BCELoss() 98 | 99 | # Initialize generator and discriminator 100 | generator = Generator() 101 | discriminator = Discriminator() 102 | 103 | if cuda: 104 | generator.cuda() 105 | discriminator.cuda() 106 | adversarial_loss.cuda() 107 | 108 | # Configure data loader 109 | os.makedirs('../data/fashionmnist', exist_ok=True) 110 | dataloader = torch.utils.data.DataLoader( 111 | datasets.FashionMNIST('../data/fashionmnist', train=True, download=True, 112 | transform=transforms.Compose([ 113 | transforms.ToTensor(), 114 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 115 | ])), 116 | batch_size=opt.batch_size, shuffle=True) 117 | 118 | 119 | # Optimizers 120 | optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 121 | optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 122 | 123 | Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor 124 | 125 | # ---------- 126 | # Training 127 | # ---------- 128 | 129 | for epoch in tqdm(range(opt.n_epochs)): 130 | for i, (imgs, _) in enumerate(dataloader): 131 | 132 | # Adversarial ground truths 133 | valid = Variable(Tensor(imgs.size(0), 1).fill_(1.0), requires_grad=False) 134 | fake = Variable(Tensor(imgs.size(0), 1).fill_(0.0), requires_grad=False) 135 | 136 | # Configure input 137 | real_imgs = Variable(imgs.type(Tensor)) 138 | 139 | # ----------------- 140 | # Train Generator 141 | # ----------------- 142 | 143 | optimizer_G.zero_grad() 144 | 145 | # Sample noise as generator input 146 | z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) 147 | 148 | g_loss = 0 149 | for k in range(opt.n_paths_G): 150 | 151 | # Generate a batch of images 152 | gen_imgs = generator.paths[k](z) 153 | 154 | # Loss measures generator's ability to fool the discriminator 155 | validity, classifier = discriminator(gen_imgs) 156 | g_loss += adversarial_loss(validity, valid) 157 | 158 | # Loss measures classifier's ability to classify various generators 159 | target = Variable(Tensor(imgs.size(0)).fill_(k), requires_grad=False) 160 | target = target.type(torch.cuda.LongTensor) 161 | g_loss += F.nll_loss(classifier, target)*0.1 162 | 163 | g_loss.backward() 164 | optimizer_G.step() 165 | 166 | # ------------------------------------ 167 | # Train Discriminator and Classifier 168 | # ------------------------------------ 169 | 170 | optimizer_D.zero_grad() 171 | 172 | d_loss = 0 173 | validity, classifier = discriminator(real_imgs) 174 | real_loss = adversarial_loss(validity, valid) 175 | temp = [] 176 | for k in range(opt.n_paths_G): 177 | 178 | # Generate a batch of images 179 | gen_imgs = generator.paths[k](z).view(imgs.shape[0], *img_shape) 180 | temp.append(gen_imgs[0:(100//opt.n_paths_G), :]) 181 | 182 | # Loss measures discriminator's ability to classify real from generated samples 183 | validity, classifier = discriminator(gen_imgs.detach()) 184 | fake_loss = adversarial_loss(validity, fake) 185 | d_loss += (real_loss + fake_loss) / 2 186 | 187 | # Loss measures classifier's ability to classify various generators 188 | target = Variable(Tensor(imgs.size(0)).fill_(k), requires_grad=False) 189 | target = target.type(torch.cuda.LongTensor) 190 | d_loss += F.nll_loss(classifier, target)*0.1 191 | 192 | plot_imgs = torch.cat(temp, dim=0) 193 | plot_imgs.detach() 194 | 195 | d_loss.backward() 196 | optimizer_D.step() 197 | 198 | #print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, i, len(dataloader), 199 | #d_loss.item(), g_loss.item())) 200 | 201 | batches_done = epoch * len(dataloader) + i 202 | if batches_done % opt.sample_interval == 0: 203 | save_image(plot_imgs[:100], 'images_ensemble_fashionmnist10/%d.png' % batches_done, nrow=10, normalize=True) 204 | 205 | -------------------------------------------------------------------------------- /Stackelberg GAN/Gaussian mixture/gan_stackelberg_mG.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import numpy as np 4 | import math 5 | 6 | import torchvision.transforms as transforms 7 | from torchvision.utils import save_image 8 | 9 | from torch.utils.data import DataLoader 10 | from torchvision import datasets 11 | from torch.autograd import Variable 12 | 13 | import torch.nn as nn 14 | import torch.nn.functional as F 15 | import torch 16 | import shutil 17 | 18 | import matplotlib.pyplot as plt 19 | plt.switch_backend('agg') 20 | import seaborn as sns 21 | import matplotlib 22 | 23 | #os.environ["CUDA_VISIBLE_DEVICES"] = "1" 24 | 25 | os.makedirs('images_ensemble_mG', exist_ok=True) 26 | shutil.rmtree('images_ensemble_mG') 27 | os.makedirs('images_ensemble_mG', exist_ok=True) 28 | 29 | parser = argparse.ArgumentParser() 30 | parser.add_argument('--n_epochs', type=int, default=200, help='number of epochs of training') 31 | parser.add_argument('--batch_size', type=int, default=64, help='size of the batches') 32 | parser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate') 33 | parser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient') 34 | parser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient') 35 | parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation') 36 | parser.add_argument('--latent_dim', type=int, default=2, help='dimensionality of the latent space') 37 | parser.add_argument('--img_size', type=int, default=28, help='size of each image dimension') 38 | parser.add_argument('--channels', type=int, default=1, help='number of image channels') 39 | parser.add_argument('--sample_interval', type=int, default=400, help='interval betwen image samples') 40 | parser.add_argument('--n_paths_D', type=int, default=1, help='number of paths of discriminator') 41 | parser.add_argument('--n_paths_G', type=int, default=8, help='number of paths of generator') 42 | opt = parser.parse_args() 43 | print(opt) 44 | 45 | #np.random.seed(1) 46 | #torch.manual_seed(1) 47 | #if torch.cuda.is_available(): 48 | # torch.cuda.manual_seed(1) 49 | 50 | cuda = True if torch.cuda.is_available() else False 51 | 52 | class Generator(nn.Module): 53 | def __init__(self): 54 | super(Generator, self).__init__() 55 | 56 | def block(in_feat, out_feat, normalize=True): 57 | layers = [nn.Linear(in_feat, out_feat)] 58 | if normalize: 59 | layers.append(nn.BatchNorm1d(out_feat, 0.8)) 60 | layers.append(nn.LeakyReLU(0.2, inplace=True)) 61 | return layers 62 | 63 | modules = nn.ModuleList() 64 | for _ in range(opt.n_paths_G): 65 | modules.append(nn.Sequential( 66 | *block(opt.latent_dim, 32, normalize=False), 67 | nn.Linear(32, 2), 68 | nn.Tanh() 69 | )) 70 | self.paths = modules 71 | 72 | def forward(self, z): 73 | img = [] 74 | for path in self.paths: 75 | img.append(path(z)) 76 | img = torch.cat(img, dim=1) 77 | return img 78 | 79 | class Discriminator(nn.Module): 80 | def __init__(self): 81 | super(Discriminator, self).__init__() 82 | modules = nn.ModuleList() 83 | for _ in range(opt.n_paths_D): 84 | modules.append(nn.Sequential( 85 | nn.Linear(2, 512), 86 | nn.LeakyReLU(0.2, inplace=True), 87 | nn.Linear(512, 256), 88 | nn.LeakyReLU(0.2, inplace=True), 89 | nn.Linear(256, 1), 90 | nn.Sigmoid() 91 | )) 92 | self.paths = modules 93 | 94 | def forward(self, img): 95 | img_flat = img 96 | validity = [] 97 | for path in self.paths: 98 | validity.append(path(img_flat)) 99 | validity = torch.cat(validity, dim=1) 100 | return validity 101 | 102 | # Loss function 103 | adversarial_loss = torch.nn.BCELoss() 104 | 105 | # Initialize generator and discriminator 106 | generator = Generator() 107 | discriminator = Discriminator() 108 | 109 | if cuda: 110 | generator.cuda() 111 | discriminator.cuda() 112 | adversarial_loss.cuda() 113 | 114 | # Configure data loader 115 | n_mixture = 8 116 | radius = 1 117 | std = 0.01 118 | thetas = np.linspace(0, 2 * (1-1/n_mixture) * np.pi, n_mixture) 119 | xs, ys = radius * np.sin(thetas), radius * np.cos(thetas) 120 | data_size = 1000*n_mixture 121 | data = torch.zeros(data_size, 2) 122 | for i in range(data_size): 123 | coin = np.random.randint(0, n_mixture) 124 | data[i, :] = torch.normal(mean=torch.Tensor([xs[coin], ys[coin]]), std=std*torch.ones(1, 2)) 125 | 126 | 127 | # Optimizers 128 | optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 129 | optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 130 | 131 | Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor 132 | 133 | # ---------- 134 | # Training 135 | # ---------- 136 | n_batch = math.ceil(data_size/opt.batch_size) 137 | 138 | for epoch in range(opt.n_epochs): 139 | colors = matplotlib.cm.rainbow(np.linspace(0, 1, 1+opt.n_paths_G)) 140 | plt.plot(data[:, 0].cpu().numpy(), data[:, 1].cpu().numpy(), color=colors[0], marker='.', linestyle='None') 141 | z = Variable(Tensor(np.random.normal(0, 1, (8000//opt.n_paths_G, opt.latent_dim)))) 142 | for k in range(opt.n_paths_G): 143 | gen_data = generator.paths[k](z).detach() 144 | plt.plot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), color=colors[1+k], marker='.', linestyle='None') 145 | 146 | for i in range(n_batch): 147 | 148 | imgs = data[i*opt.batch_size:min((i+1)*opt.batch_size, data_size-1), :] 149 | 150 | # Adversarial ground truths 151 | valid = Variable(Tensor(imgs.size(0), opt.n_paths_D).fill_(1.0), requires_grad=False) 152 | fake = Variable(Tensor(imgs.size(0), opt.n_paths_D).fill_(0.0), requires_grad=False) 153 | 154 | # Configure input 155 | real_imgs = Variable(imgs.type(Tensor)) 156 | 157 | # ----------------- 158 | # Train Generator 159 | # ----------------- 160 | 161 | optimizer_G.zero_grad() 162 | 163 | # Sample noise as generator input 164 | z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) 165 | 166 | g_loss = 0 167 | for k in range(opt.n_paths_G): 168 | 169 | # Generate a batch of images 170 | gen_imgs = generator.paths[k](z) 171 | 172 | # Loss measures generator's ability to fool the discriminator 173 | g_loss += adversarial_loss(discriminator(gen_imgs), valid) 174 | 175 | g_loss.backward() 176 | optimizer_G.step() 177 | 178 | # --------------------- 179 | # Train Discriminator 180 | # --------------------- 181 | 182 | optimizer_D.zero_grad() 183 | 184 | d_loss = 0 185 | real_loss = adversarial_loss(discriminator(real_imgs), valid) 186 | for k in range(opt.n_paths_G): 187 | 188 | # Generate a batch of images 189 | gen_imgs = generator.paths[k](z) 190 | 191 | # Measure discriminator's ability to classify real from generated samples 192 | fake_loss = adversarial_loss(discriminator(gen_imgs.detach()), fake) 193 | d_loss += (real_loss + fake_loss) / 2 194 | 195 | d_loss.backward() 196 | optimizer_D.step() 197 | 198 | print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f] [D value: %f]" % (epoch+1, opt.n_epochs, i, n_batch, 199 | d_loss.item(), g_loss.item(), discriminator(real_imgs).mean(0).mean().item())) 200 | 201 | colors = matplotlib.cm.rainbow(np.linspace(0, 1, 1+opt.n_paths_G)) 202 | plt.plot(data[:, 0].cpu().numpy(), data[:, 1].cpu().numpy(), color=colors[0], marker='.', linestyle='None') 203 | 204 | z = Variable(Tensor(np.random.normal(0, 1, (8000//opt.n_paths_G, opt.latent_dim)))) 205 | temp = [] 206 | for k in range(opt.n_paths_G): 207 | # temp.append(generator.paths[k](z).detach()) 208 | # gen_data = torch.cat(temp, dim=0) 209 | # sns.jointplot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), kind='kde', stat_func=None) 210 | gen_data = generator.paths[k](z).detach() 211 | plt.plot(gen_data[:, 0].cpu().numpy(), gen_data[:, 1].cpu().numpy(), color=colors[1+k], marker='.', linestyle='None') 212 | 213 | plt.savefig('images_ensemble_mG/%d.png' % epoch) 214 | plt.close('all') 215 | -------------------------------------------------------------------------------- /Stackelberg GAN/MNIST/gan_mnist_classifier.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import numpy as np 4 | import math 5 | 6 | import torchvision.transforms as transforms 7 | from torchvision.utils import save_image 8 | 9 | from torch.utils.data import DataLoader 10 | from torchvision import datasets 11 | from torch.autograd import Variable 12 | from tqdm import tqdm 13 | 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | import torch 17 | import shutil 18 | 19 | os.makedirs('images_ensemble_mnist10_classifier_small', exist_ok=True) 20 | shutil.rmtree('images_ensemble_mnist10_classifier_small') 21 | os.makedirs('images_ensemble_mnist10_classifier_small', exist_ok=True) 22 | 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('--n_epochs', type=int, default=500, help='number of epochs of training') 25 | parser.add_argument('--batch_size', type=int, default=100, help='size of the batches') 26 | parser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate') 27 | parser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient') 28 | parser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient') 29 | parser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation') 30 | parser.add_argument('--latent_dim', type=int, default=100, help='dimensionality of the latent space') 31 | parser.add_argument('--img_size', type=int, default=28, help='size of each image dimension') 32 | parser.add_argument('--channels', type=int, default=1, help='number of image channels') 33 | parser.add_argument('--sample_interval', type=int, default=400, help='interval betwen image samples') 34 | parser.add_argument('--n_paths_G', type=int, default=10, help='number of paths of generator') 35 | parser.add_argument('--classifier_para', type=float, default=1.0, help='regularization parameter for classifier') 36 | opt = parser.parse_args() 37 | print(opt) 38 | 39 | img_shape = (opt.channels, opt.img_size, opt.img_size) 40 | 41 | cuda = True if torch.cuda.is_available() else False 42 | 43 | class Generator(nn.Module): 44 | def __init__(self): 45 | super(Generator, self).__init__() 46 | 47 | def block(in_feat, out_feat, normalize=True): 48 | layers = [nn.Linear(in_feat, out_feat)] 49 | if normalize: 50 | layers.append(nn.BatchNorm1d(out_feat, 0.8)) 51 | layers.append(nn.LeakyReLU(0.2, inplace=True)) 52 | return layers 53 | 54 | modules = nn.ModuleList() 55 | for _ in range(opt.n_paths_G): 56 | modules.append(nn.Sequential( 57 | *block(opt.latent_dim, 128), 58 | *block(128, 512), 59 | #*block(256, 512), 60 | #*block(512, 512), 61 | #*block(512, 1024), 62 | nn.Linear(512, int(np.prod(img_shape))), 63 | nn.Tanh() 64 | )) 65 | self.paths = modules 66 | 67 | def forward(self, z): 68 | img = [] 69 | for path in self.paths: 70 | img.append(path(z).view(img.size(0), *img_shape)) 71 | img = torch.cat(img, dim=0) 72 | return img 73 | 74 | class Discriminator(nn.Module): 75 | def __init__(self): 76 | super(Discriminator, self).__init__() 77 | self.fc1 = nn.Linear(int(np.prod(img_shape)), 512) 78 | self.lr1 = nn.LeakyReLU(0.2, inplace=True) 79 | self.fc2 = nn.Linear(512, 256) 80 | self.lr2 = nn.LeakyReLU(0.2, inplace=True) 81 | modules = nn.ModuleList() 82 | modules.append(nn.Sequential( 83 | nn.Linear(256, 1), 84 | nn.Sigmoid(), 85 | )) 86 | modules.append(nn.Sequential( 87 | nn.Linear(256, 10), 88 | )) 89 | self.paths = modules 90 | 91 | def forward(self, img): 92 | img_flat = img.view(img.size(0), -1) 93 | img_flat = self.lr2(self.fc2(self.lr1(self.fc1(img_flat)))) 94 | validity = self.paths[0](img_flat) 95 | classifier = F.log_softmax(self.paths[1](img_flat), dim=1) 96 | return validity, classifier 97 | 98 | # Loss function 99 | adversarial_loss = torch.nn.BCELoss() 100 | 101 | # Initialize generator and discriminator 102 | generator = Generator() 103 | discriminator = Discriminator() 104 | 105 | if cuda: 106 | generator.cuda() 107 | discriminator.cuda() 108 | adversarial_loss.cuda() 109 | 110 | # Configure data loader 111 | os.makedirs('../data/mnist', exist_ok=True) 112 | dataloader = torch.utils.data.DataLoader( 113 | datasets.MNIST('../data/mnist', train=True, download=True, 114 | transform=transforms.Compose([ 115 | transforms.ToTensor(), 116 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 117 | ])), 118 | batch_size=opt.batch_size, shuffle=True) 119 | 120 | 121 | # Optimizers 122 | optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 123 | optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2)) 124 | 125 | Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor 126 | 127 | # ---------- 128 | # Training 129 | # ---------- 130 | 131 | # print("--------Loading Model--------") 132 | # checkpoint = torch.load('checkpoint_images_ensemble_fashionmnist10_classifier.tar') 133 | # generator.load_state_dict(checkpoint['g_state_dict']) 134 | # discriminator.load_state_dict(checkpoint['d_state_dict']) 135 | 136 | for epoch in tqdm(range(opt.n_epochs)): 137 | for i, (imgs, _) in enumerate(dataloader): 138 | 139 | # Adversarial ground truths 140 | valid = Variable(Tensor(imgs.size(0), 1).fill_(1.0), requires_grad=False) 141 | fake = Variable(Tensor(imgs.size(0), 1).fill_(0.0), requires_grad=False) 142 | 143 | # Configure input 144 | real_imgs = Variable(imgs.type(Tensor)) 145 | 146 | # ----------------- 147 | # Train Generator 148 | # ----------------- 149 | 150 | optimizer_G.zero_grad() 151 | 152 | # Sample noise as generator input 153 | z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim)))) 154 | 155 | g_loss = 0 156 | for k in range(opt.n_paths_G): 157 | 158 | # Generate a batch of images 159 | gen_imgs = generator.paths[k](z) 160 | 161 | # Loss measures generator's ability to fool the discriminator 162 | validity, classifier = discriminator(gen_imgs) 163 | g_loss += adversarial_loss(validity, valid) 164 | 165 | # Loss measures classifier's ability to classify various generators 166 | target = Variable(Tensor(imgs.size(0)).fill_(k), requires_grad=False) 167 | target = target.type(torch.cuda.LongTensor) 168 | g_loss += F.nll_loss(classifier, target)*opt.classifier_para 169 | 170 | g_loss.backward() 171 | optimizer_G.step() 172 | 173 | # ------------------------------------ 174 | # Train Discriminator and Classifier 175 | # ------------------------------------ 176 | 177 | optimizer_D.zero_grad() 178 | 179 | d_loss = 0 180 | validity, classifier = discriminator(real_imgs) 181 | real_loss = adversarial_loss(validity, valid) 182 | temp = [] 183 | for k in range(opt.n_paths_G): 184 | 185 | # Generate a batch of images 186 | gen_imgs = generator.paths[k](z).view(imgs.shape[0], *img_shape) 187 | temp.append(gen_imgs[0:(100//opt.n_paths_G), :]) 188 | 189 | # Loss measures discriminator's ability to classify real from generated samples 190 | validity, classifier = discriminator(gen_imgs.detach()) 191 | fake_loss = adversarial_loss(validity, fake) 192 | d_loss += (real_loss + fake_loss) / 2 193 | 194 | # Loss measures classifier's ability to classify various generators 195 | target = Variable(Tensor(imgs.size(0)).fill_(k), requires_grad=False) 196 | target = target.type(torch.cuda.LongTensor) 197 | d_loss += F.nll_loss(classifier, target)*opt.classifier_para 198 | 199 | plot_imgs = torch.cat(temp, dim=0) 200 | plot_imgs.detach() 201 | 202 | d_loss.backward() 203 | optimizer_D.step() 204 | 205 | #print ("[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]" % (epoch, opt.n_epochs, i, len(dataloader), 206 | #d_loss.item(), g_loss.item())) 207 | 208 | batches_done = epoch * len(dataloader) + i 209 | if batches_done % opt.sample_interval == 0: 210 | save_image(plot_imgs[:100], 'images_ensemble_mnist10_classifier_small/%d.png' % batches_done, nrow=10, normalize=True) 211 | 212 | #if epoch % 10 == 0: 213 | #torch.save({ 214 | #'epoch': epoch + 1, 215 | #'g_state_dict': generator.state_dict(), 216 | #'d_state_dict': discriminator.state_dict(), 217 | #}, 'checkpoint_images_ensemble_fashionmnist10_classifier.tar') 218 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Stackelberg GAN/CIFAR-10/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | from __future__ import print_function 3 | from __future__ import absolute_import 4 | from functools import partial 5 | 6 | import os 7 | import numpy as np 8 | import tensorflow as tf 9 | from ops import lrelu, linear, conv2d, deconv2d 10 | from utils import make_batches, Prior, conv_out_size_same, create_image_grid, merge 11 | 12 | batch_norm = partial(tf.contrib.layers.batch_norm, 13 | decay=0.9, 14 | updates_collections=None, 15 | epsilon=1e-5, 16 | scale=True) 17 | 18 | 19 | class SGAN(object):#Stackelberg GAN 20 | 21 | def __init__(self, 22 | model_name='SGAN', 23 | beta=1.0, 24 | num_z=128, 25 | num_gens=4, 26 | d_batch_size=64, 27 | g_batch_size=32, 28 | z_prior="uniform", 29 | same_input=True, 30 | learning_rate1=0.0002, 31 | learning_rate2=0.0002, 32 | img_size=(32, 32, 3), # (height, width, channels) 33 | g_num_conv_layers=3, 34 | d_num_conv_layers=3, 35 | num_gen_feature_maps=128, # number of feature maps of generator 36 | num_dis_feature_maps=128, # number of feature maps of discriminator 37 | sample_fp=None, 38 | sample_by_gen_fp=None, 39 | num_epochs=25000, 40 | random_seed=6789, 41 | checkpoint_dir=None): 42 | self.beta = beta 43 | self.num_z = num_z 44 | self.num_gens = num_gens 45 | self.d_batch_size = d_batch_size 46 | self.g_batch_size = g_batch_size 47 | self.z_prior = Prior(z_prior) 48 | self.same_input = same_input 49 | self.learning_rate1 = learning_rate1 50 | self.learning_rate2 = learning_rate2 51 | self.num_epochs = num_epochs 52 | self.img_size = img_size 53 | self.g_num_conv_layers = g_num_conv_layers 54 | self.d_num_conv_layers = d_num_conv_layers 55 | self.num_gen_feature_maps = num_gen_feature_maps 56 | self.num_dis_feature_maps = num_dis_feature_maps 57 | self.sample_fp = sample_fp 58 | self.sample_by_gen_fp = sample_by_gen_fp 59 | self.random_seed = random_seed 60 | self.checkpoint_dir = checkpoint_dir 61 | 62 | def _init(self): 63 | self.epoch = 0 64 | 65 | # TensorFlow's initialization 66 | self.tf_graph = tf.Graph() 67 | self.tf_config = tf.ConfigProto() 68 | self.tf_config.gpu_options.allow_growth = True 69 | self.tf_config.log_device_placement = False 70 | self.tf_config.allow_soft_placement = True 71 | self.tf_session = tf.Session(config=self.tf_config, graph=self.tf_graph) 72 | 73 | np.random.seed(self.random_seed) 74 | with self.tf_graph.as_default(): 75 | tf.set_random_seed(self.random_seed) 76 | 77 | def _build_model(self): 78 | arr = np.array([i // self.g_batch_size for i in range(self.g_batch_size * self.num_gens)]) 79 | d_mul_labels = tf.constant(arr, dtype=tf.int32) 80 | 81 | self.x = tf.placeholder(tf.float32, [None, 82 | self.img_size[0], self.img_size[1], self.img_size[2]], 83 | name="real_data") 84 | self.z = tf.placeholder(tf.float32, [self.g_batch_size * self.num_gens, self.num_z], name='noise') 85 | 86 | # create generator G 87 | self.g = self._create_generator(self.z) 88 | 89 | # create sampler to generate samples 90 | self.sampler = self._create_generator(self.z, train=False, reuse=True) 91 | 92 | # create discriminator D 93 | 94 | d_bin_x_logits, d_mul_x_logits = self._create_discriminator(self.x) 95 | d_bin_g_logits, d_mul_g_logits = self._create_discriminator(self.g, reuse=True) 96 | 97 | # define loss functions 98 | self.d_bin_x_loss = tf.reduce_mean( 99 | tf.nn.sigmoid_cross_entropy_with_logits( 100 | logits=d_bin_x_logits, labels=tf.ones_like(d_bin_x_logits)), 101 | name='d_bin_x_loss') 102 | self.d_bin_g_loss = tf.reduce_mean( 103 | tf.nn.sigmoid_cross_entropy_with_logits( 104 | logits=d_bin_g_logits, labels=tf.zeros_like(d_bin_g_logits)), 105 | name='d_bin_g_loss') 106 | self.d_bin_loss = tf.add(self.d_bin_x_loss, self.d_bin_g_loss, name='d_bin_loss') 107 | self.d_mul_loss = tf.reduce_mean( 108 | tf.nn.sparse_softmax_cross_entropy_with_logits( 109 | logits=d_mul_g_logits, labels=d_mul_labels), 110 | name="d_mul_loss") 111 | self.d_loss = tf.add(self.d_bin_loss, tf.multiply(self.beta, self.d_mul_loss), name="d_loss") 112 | 113 | self.g_bin_loss = tf.reduce_mean( 114 | tf.nn.sigmoid_cross_entropy_with_logits( 115 | logits=d_bin_g_logits, labels=tf.ones_like(d_bin_g_logits)), 116 | name="g_bin_loss") 117 | self.g_mul_loss = tf.multiply(self.beta, self.d_mul_loss, name='g_mul_loss') 118 | self.g_loss = tf.add(self.g_bin_loss, self.g_mul_loss, name="g_loss") 119 | 120 | # create optimizers 121 | self.d_opt = self._create_optimizer(self.d_loss, scope='discriminator', 122 | lr=self.learning_rate1) 123 | self.g_opt = self._create_optimizer(self.g_loss, scope='generator', 124 | lr=self.learning_rate2) 125 | self.saver = tf.train.Saver(max_to_keep=10) 126 | def _create_generator(self, z, train=True, reuse=False, name="generator"): 127 | out_size = [(conv_out_size_same(self.img_size[0], 2), 128 | conv_out_size_same(self.img_size[1], 2), 129 | self.num_gen_feature_maps)] 130 | for i in range(self.g_num_conv_layers - 1): 131 | out_size = [(conv_out_size_same(out_size[0][0], 2), 132 | conv_out_size_same(out_size[0][1], 2), 133 | out_size[0][2] * 2)] + out_size 134 | 135 | print(out_size) 136 | with tf.variable_scope(name) as scope: 137 | if reuse: 138 | scope.reuse_variables() 139 | 140 | z_split = tf.split(z, self.num_gens, axis=0) 141 | h0 = [] 142 | for i, var in enumerate(z_split): 143 | h0.append(tf.nn.relu(linear(var, out_size[0][0] * out_size[0][1] * out_size[0][2], 144 | scope='g_h0_linear{}'.format(i), stddev=0.02),name="g_h0_relu{}".format(i))) 145 | 146 | g_out = [] 147 | for k, var in enumerate(h0): 148 | var = tf.reshape(var, [self.g_batch_size, out_size[0][0], out_size[0][1], out_size[0][2]]) 149 | for i in range(1, self.g_num_conv_layers): 150 | var = tf.nn.relu( 151 | deconv2d(var, 152 | [self.g_batch_size, out_size[i][0], out_size[i][1], out_size[i][2]], 153 | stddev=0.02, name="g{}_h{}_deconv".format(k,i)), 154 | name="g{}_h{}_relu".format(k,i)) 155 | 156 | g_out.append(tf.nn.tanh( 157 | deconv2d(var, 158 | [self.g_batch_size, self.img_size[0], self.img_size[1], self.img_size[2]], 159 | stddev=0.02, name="g{}_out_deconv".format(k,i)), 160 | name="g{}_out_tanh".format(k,i))) 161 | 162 | g_out = tf.concat(g_out, axis=0, name="g_out") 163 | 164 | 165 | return g_out 166 | 167 | def _create_discriminator(self, x, train=True, reuse=False, name="discriminator"): 168 | with tf.variable_scope(name) as scope: 169 | if reuse: 170 | scope.reuse_variables() 171 | 172 | h = x 173 | for i in range(self.d_num_conv_layers): 174 | h = lrelu(batch_norm(conv2d(h, self.num_dis_feature_maps * (2 ** i), 175 | stddev=0.02, name="d_h{}_conv".format(i)), 176 | is_training=train, 177 | scope="d_bn{}".format(i))) 178 | 179 | dim = h.get_shape()[1:].num_elements() 180 | h = tf.reshape(h, [-1, dim]) 181 | d_bin_logits = linear(h, 1, scope='d_bin_logits') 182 | d_mul_logits = linear(h, self.num_gens, scope='d_mul_logits') 183 | return d_bin_logits, d_mul_logits 184 | 185 | def _create_optimizer(self, loss, scope, lr): 186 | params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope) 187 | opt = tf.train.AdamOptimizer(lr, beta1=0.5) 188 | grads = opt.compute_gradients(loss, var_list=params) 189 | train_op = opt.apply_gradients(grads) 190 | return train_op 191 | 192 | def fit(self, x): 193 | if (not hasattr(self, 'epoch')) or self.epoch == 0: 194 | self._init() 195 | with self.tf_graph.as_default(): 196 | self._build_model() 197 | self.tf_session.run(tf.global_variables_initializer()) 198 | if self.load(): 199 | print('load the checkpoint!') 200 | else: 201 | print('cannot load the checkpoint and init all the varibale') 202 | 203 | num_data = x.shape[0] - x.shape[0] % self.d_batch_size 204 | batches = make_batches(num_data, self.d_batch_size) 205 | best_is = 0.0 206 | while (self.epoch < self.num_epochs): 207 | for batch_idx, (batch_start, batch_end) in enumerate(batches): 208 | batch_size = batch_end - batch_start 209 | 210 | x_batch = x[batch_start:batch_end] 211 | if self.same_input: 212 | z_batch = self.z_prior.sample([self.g_batch_size, self.num_z]).astype(np.float32) 213 | z_batch = np.vstack([z_batch] * self.num_gens) 214 | else: 215 | z_batch = self.z_prior.sample([self.g_batch_size * self.num_gens, self.num_z]).astype(np.float32) 216 | 217 | # update discriminator D 218 | d_bin_loss, d_mul_loss, d_loss, _ = self.tf_session.run( 219 | [self.d_bin_loss, self.d_mul_loss, self.d_loss, self.d_opt], 220 | feed_dict={self.x: x_batch, self.z: z_batch}) 221 | 222 | # update generator G 223 | g_bin_loss, g_mul_loss, g_loss, _ = self.tf_session.run( 224 | [self.g_bin_loss, self.g_mul_loss, self.g_loss, self.g_opt], 225 | feed_dict={self.z: z_batch}) 226 | 227 | self.epoch += 1 228 | print("Epoch: [%4d/%4d] d_bin_loss: %.5f, d_mul_loss: %.5f, d_loss: %.5f," 229 | " g_bin_loss: %.5f, g_mul_loss: %.5f, g_loss: %.5f" % (self.epoch, self.num_epochs, 230 | d_bin_loss, d_mul_loss, d_loss, g_bin_loss, g_mul_loss, g_loss)) 231 | # print("Epoch: [%4d/%4d] d_bin_loss: %.5f,g_bin_loss: %.5f" % (self.epoch, self.num_epochs, 232 | # d_bin_loss, g_bin_loss)) 233 | if self.epoch%10 == 0: 234 | self._samples(self.sample_fp.format(epoch=self.epoch+1)) 235 | 236 | if not os.path.exists(self.checkpoint_dir): 237 | os.makedirs(self.checkpoint_dir) 238 | self.saver.save(self.tf_session, os.path.join(self.checkpoint_dir, "classifier_mode_checkpoint"))#+str(self.num_gens)+"epoch_"+str(self.num_epochs)+"num_g_maps_"+str(self.num_gen_feature_maps))) 239 | self._samples_by_gen(self.sample_by_gen_fp) 240 | 241 | def predict(self): 242 | if (not hasattr(self, 'epoch')) or self.epoch == 0: 243 | self._init() 244 | with self.tf_graph.as_default(): 245 | self._build_model() 246 | self.tf_session.run(tf.global_variables_initializer()) 247 | if self.load(): 248 | print('load the checkpoint!') 249 | else: 250 | print('cannot load the checkpoint and init all the varibale') 251 | self._samples_by_gen(self.sample_by_gen_fp) 252 | 253 | 254 | def _generate(self, num_samples=100): 255 | sess = self.tf_session 256 | batch_size = self.g_batch_size * self.num_gens 257 | num = ((num_samples - 1) // batch_size + 1) * batch_size 258 | z = self.z_prior.sample([num, self.num_z]).astype(np.float32) 259 | x = np.zeros([num, self.img_size[0], self.img_size[1], self.img_size[2]], 260 | dtype=np.float32) 261 | batches = make_batches(num, batch_size) 262 | for batch_idx, (batch_start, batch_end) in enumerate(batches): 263 | z_batch = z[batch_start:batch_end] 264 | x[batch_start:batch_end] = sess.run(self.sampler, 265 | feed_dict={self.z: z_batch}) 266 | f_x = np.reshape(x, [self.num_gens,-1, self.img_size[0], self.img_size[1], self.img_size[2]]) 267 | f_x = f_x[:,0::7,:,:,:] 268 | f_x = np.reshape(f_x,[num_samples,self.img_size[0], self.img_size[1], self.img_size[2]]) 269 | # idx = np.random.permutation(num)[:num_samples] 270 | # x = (x[idx] + 1.0) / 2.0 271 | # x = x[idx] 272 | x = (f_x+1)/2 273 | return x 274 | 275 | def _samples(self, filepath, tile_shape=(10, 10)): 276 | if not os.path.exists(os.path.dirname(filepath)): 277 | os.makedirs(os.path.dirname(filepath)) 278 | 279 | num_samples = tile_shape[0] * tile_shape[1] 280 | x = self._generate(num_samples) 281 | imgs = create_image_grid(x, img_size=self.img_size, tile_shape=tile_shape) 282 | import scipy.misc 283 | scipy.misc.imsave(filepath, imgs) 284 | 285 | def _samples_by_gen(self, filepath): 286 | if not os.path.exists(filepath): 287 | os.makedirs(filepath) 288 | 289 | num_samples = self.num_gens * 4000 290 | tile_shape = (1,1) 291 | 292 | sess = self.tf_session 293 | img_per_gen = num_samples // self.num_gens 294 | # x = np.zeros([num_samples, self.img_size[0], self.img_size[1], self.img_size[2]], 295 | # dtype=np.float32) 296 | counter = 0 297 | for i in range(0, img_per_gen, self.g_batch_size): 298 | z_batch = self.z_prior.sample([self.g_batch_size * self.num_gens, self.num_z]).astype(np.float32) 299 | samples = sess.run(self.sampler, feed_dict={self.z: z_batch}) 300 | 301 | for gen in range(self.num_gens): 302 | 303 | tmp_ = samples[gen * self.g_batch_size:gen * self.g_batch_size + min(self.g_batch_size, img_per_gen)] 304 | for x in tmp_: 305 | counter = counter+1 306 | x = x.reshape(1, 32, 32, 3) 307 | x = (x + 1.0) / 2.0 308 | imgs = merge(x, [1,1]) 309 | import scipy.misc 310 | scipy.misc.imsave(os.path.join(filepath, "samples_"+str(counter)+".png"), imgs) 311 | def load(self): 312 | print('Being to load the checkpoint') 313 | ckpt = tf.train.get_checkpoint_state(self.checkpoint_dir) 314 | if ckpt and ckpt.model_checkpoint_path: 315 | self.saver.restore(self.tf_session, ckpt.model_checkpoint_path) 316 | return True 317 | else: 318 | return False 319 | --------------------------------------------------------------------------------