In [7]:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.Session()


Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz

In [2]:
tf.reset_default_graph() #helps with the get_variable usage by clearing the variables

mb_size = 100
Z_dim = 100

X = tf.placeholder(tf.float32, shape=[mb_size, 784], name='X')

#D_W1 = tf.Variable(xavier_init([784, 128]), name='D_W1')
D_W1 = tf.get_variable("D_W1", shape=[784, 128],
           initializer=tf.contrib.layers.xavier_initializer())
D_b1 = tf.Variable(tf.zeros(shape=[128]), name='D_b1')

#D_W2 = tf.Variable(xavier_init([128, 1]), name='D_W2')
D_W2 = tf.get_variable("D_W2", shape=[128, 1],
           initializer=tf.contrib.layers.xavier_initializer())
D_b2 = tf.Variable(tf.zeros(shape=[1]), name='D_b2')

theta_D = [D_W1, D_W2, D_b1, D_b2]

# Generator Net
Z = tf.placeholder(tf.float32, shape=[mb_size, 100], name='Z')

#G_W1 = tf.Variable(xavier_init([100, 128]), name='G_W1')
G_W1 = tf.get_variable('G_W1',shape=[100, 128],
           initializer=tf.contrib.layers.xavier_initializer())
G_b1 = tf.Variable(tf.zeros(shape=[128]), name='G_b1')

#G_W2 = tf.Variable(xavier_init([128, 784]), name='G_W2')
G_W2 = tf.get_variable('G_W2',shape=[128,784],
                       initializer=tf.contrib.layers.xavier_initializer())
G_b2 = tf.Variable(tf.zeros(shape=[784]), name='G_b2')

theta_G = [G_W1, G_W2, G_b1, G_b2]

In [3]:
def generator(z):
    G_h1 = tf.nn.relu(tf.matmul(z, G_W1) + G_b1)
    G_log_prob = tf.matmul(G_h1, G_W2) + G_b2
    G_prob = tf.nn.sigmoid(G_log_prob)

    return G_prob


def discriminator(x):
    D_h1 = tf.nn.relu(tf.matmul(x, D_W1) + D_b1)
    D_logit = tf.matmul(D_h1, D_W2) + D_b2
    D_prob = tf.nn.sigmoid(D_logit)

    return D_prob, D_logit

In [4]:
G_sample = generator(Z)
D_real, D_logit_real = discriminator(X)
D_fake, D_logit_fake = discriminator(G_sample)

D_loss = -tf.reduce_mean(tf.log(D_real) + tf.log(1. - D_fake))
G_loss = -tf.reduce_mean(tf.log(D_fake))

In [24]:
def plotnum(*argv):
    if len(argv) > 0:
        #block of mnist data has been handed
        test_mnist = argv[0]
    else:
        test_mnist = sess.run(G_sample,{Z: sample_Z(mb_size, Z_dim)})
        
    number1 = np.reshape(test_mnist[0,:],(28,28))
    number2 = np.reshape(test_mnist[1,:],(28,28))
    number3 = np.reshape(test_mnist[2,:],(28,28))
    plt.subplot(1,3,1)
    plt.imshow(number1, cmap='gray')
    plt.subplot(1,3,2)
    plt.imshow(number2, cmap='gray')
    plt.subplot(1,3,3)
    plt.imshow(number3, cmap='gray')
    plt.show()

In [34]:
# Only update D(X)'s parameters, so var_list = theta_D
D_solver = tf.train.AdamOptimizer().minimize(D_loss, var_list=theta_D)
# Only update G(X)'s parameters, so var_list = theta_G
G_solver = tf.train.AdamOptimizer().minimize(G_loss, var_list=theta_G)

def sample_Z(m, n):
    '''Uniform prior for G(Z)'''
    return np.random.uniform(-1., 1., size=[m, n])

ntrain = 100000
dloss = np.zeros((ntrain))
gloss = np.zeros((ntrain))

startfresh = True
if startfresh:
    init = tf.global_variables_initializer()
    sess.run(init)

for it in range(ntrain):
    if np.mod(it,10000.)==0:
            print(it)
            plotnum()
    X_mb, _ = mnist.train.next_batch(mb_size)

    _, D_loss_curr = sess.run([D_solver, D_loss], {X: X_mb, Z: sample_Z(mb_size, Z_dim)})
    _, G_loss_curr = sess.run([G_solver, G_loss], {Z: sample_Z(mb_size, Z_dim)})
    dloss[it] = D_loss_curr
    gloss[it] = G_loss_curr


0
---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-34-7e28aeab88ce> in <module>()
     23     X_mb, _ = mnist.train.next_batch(mb_size)
     24 
---> 25     _, D_loss_curr = sess.run([D_solver, D_loss], {X: X_mb, Z: sample_Z(mb_size, Z_dim)})
     26     _, G_loss_curr = sess.run([G_solver, G_loss], {Z: sample_Z(mb_size, Z_dim)})
     27     dloss[it] = D_loss_curr

/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053 
   1054   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value beta1_power_16
	 [[Node: beta1_power_16/read = Identity[T=DT_FLOAT, _class=["loc:@D_W1"], _device="/job:localhost/replica:0/task:0/cpu:0"](beta1_power_16)]]

Caused by op u'beta1_power_16/read', defined at:
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-34-7e28aeab88ce>", line 2, in <module>
    D_solver = tf.train.AdamOptimizer().minimize(D_loss, var_list=theta_D)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 325, in minimize
    name=name)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 446, in apply_gradients
    self._create_slots([_get_variable_for(v) for v in var_list])
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/training/adam.py", line 116, in _create_slots
    trainable=False)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/ops/variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/dhocker/miniconda2/envs/tensorflow1.1/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value beta1_power_16
	 [[Node: beta1_power_16/read = Identity[T=DT_FLOAT, _class=["loc:@D_W1"], _device="/job:localhost/replica:0/task:0/cpu:0"](beta1_power_16)]]

In [35]:
plt.plot(dloss)
plt.show()



In [53]:


In [36]:
X_mb, _ = mnist.train.next_batch(mb_size)
X_mb.shape
plotnum()



In [ ]: