Skip to content

Commit f55ff0e

Browse files
committed
various updates
1 parent 9b3b284 commit f55ff0e

4 files changed

Lines changed: 100 additions & 28 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
""" Random Forest.
2+
3+
Implement Random Forest algorithm with TensorFlow, and apply it to classify
4+
handwritten digit images. This example is using the MNIST database of
5+
handwritten digits as training samples (http://yann.lecun.com/exdb/mnist/).
6+
7+
Author: Aymeric Damien
8+
Project: https://github.com/aymericdamien/TensorFlow-Examples/
9+
"""
10+
11+
from __future__ import print_function
12+
13+
import tensorflow as tf
14+
from tensorflow.contrib.tensor_forest.python import tensor_forest
15+
16+
# Ignore all GPUs, tf random forest does not benefit from it.
17+
import os
18+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
19+
20+
# Import MNIST data
21+
from tensorflow.examples.tutorials.mnist import input_data
22+
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
23+
24+
# Parameters
25+
num_steps = 10000 # Total steps to train
26+
batch_size = 512 # The number of samples per batch
27+
num_classes = 10 # The 10 digits
28+
num_features = 784 # Each image is 28x28 pixels
29+
num_trees = 100
30+
max_nodes = 1000
31+
32+
# Input and Target data
33+
X = tf.placeholder(tf.float32, shape=[None, num_features])
34+
Y = tf.placeholder(tf.float32, shape=[None, num_classes])
35+
36+
# Random Forest Parameters
37+
hparams = tensor_forest.ForestHParams(num_classes=num_classes,
38+
num_features=num_features,
39+
num_trees=num_trees,
40+
max_nodes=max_nodes).fill()
41+
# Build the Random Forest
42+
forest_graph = tensor_forest.RandomForestGraphs(hparams)
43+
# Get training graph and loss
44+
train_op = forest_graph.training_graph(X, Y)
45+
loss_op = forest_graph.training_loss(X, Y)
46+
47+
# Measure the accuracy
48+
infer_op = forest_graph.inference_graph(X)
49+
correct_prediction = tf.equal(tf.argmax(infer_op, 1), tf.argmax(Y, 1))
50+
accuracy_op = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
51+
52+
# Initialize all variables
53+
init = tf.global_variables_initializer()
54+
55+
with tf.Session() as sess:
56+
sess.run(init)
57+
58+
# Training
59+
for i in range(1, num_steps + 1):
60+
# Prepare Data
61+
# Get the next batch of MNIST data (only images are needed, not labels)
62+
batch_x, batch_y = mnist.train.next_batch(batch_size)
63+
_, l = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y})
64+
if i % 100 == 0 or i == 1:
65+
acc = sess.run(accuracy_op, feed_dict={X: batch_x, Y: batch_y})
66+
print('Step %i, Loss: %f, Acc: %f' % (i, l, acc))
67+
68+
69+

examples/3_NeuralNetworks/dcgan.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
2727

2828
# Training Params
29-
n_steps = 20000
29+
num_steps = 20000
3030
batch_size = 32
3131

3232
# Network Params
@@ -124,7 +124,7 @@ def discriminator(x, reuse=False):
124124
sess.run(init)
125125

126126
# Training
127-
for i in range(1, n_steps+1):
127+
for i in range(1, num_steps+1):
128128

129129
# Prepare Input Data
130130
# Get the next batch of MNIST data (only images are needed, not labels)

examples/3_NeuralNetworks/gan.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
3131

3232
# Training Params
33-
n_steps = 30000
33+
num_steps = 30000
3434
batch_size = 32
3535

3636
# Network Params
@@ -39,7 +39,7 @@
3939
disc_hidden_dim = 256
4040
noise_dim = 100 # Noise data points
4141

42-
# A custom initialization (see Xavier glorot init)
42+
# A custom initialization (see Xavier Glorot init)
4343
def glorot_init(shape):
4444
return tf.random_normal(shape=shape, stddev=1. / tf.sqrt(shape[0] / 2.))
4545

@@ -120,7 +120,7 @@ def discriminator(x):
120120
sess.run(init)
121121

122122
# Training
123-
for i in range(1, n_steps+1):
123+
for i in range(1, num_steps+1):
124124
# Prepare Data
125125
# Get the next batch of MNIST data (only images are needed, not labels)
126126
batch_x, _ = mnist.train.next_batch(batch_size)

examples/3_NeuralNetworks/variational_autoencoder.py

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@
66
References:
77
- Auto-Encoding Variational Bayes The International Conference on Learning
88
Representations (ICLR), Banff, 2014. D.P. Kingma, M. Welling
9+
- Understanding the difficulty of training deep feedforward neural networks.
10+
X Glorot, Y Bengio. Aistats 9, 249-256
911
- Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based
1012
learning applied to document recognition." Proceedings of the IEEE,
1113
86(11):2278-2324, November 1998.
1214
1315
Links:
1416
- [VAE Paper] https://arxiv.org/abs/1312.6114
17+
- [Xavier Glorot Init](www.cs.cmu.edu/~bhiksha/courses/deeplearning/Fall.../AISTATS2010_Glorot.pdf).
1518
- [MNIST Dataset] http://yann.lecun.com/exdb/mnist/
1619
1720
Author: Aymeric Damien
@@ -30,15 +33,15 @@
3033

3134
# Parameters
3235
learning_rate = 0.001
33-
n_steps = 20000
34-
batch_size = 32
36+
num_steps = 30000
37+
batch_size = 64
3538

3639
# Network Parameters
3740
image_dim = 784 # MNIST images are 28x28 pixels
38-
hidden_dim = 256
41+
hidden_dim = 512
3942
latent_dim = 2
4043

41-
# A custom initialization (see Xavier glorot init)
44+
# A custom initialization (see Xavier Glorot init)
4245
def glorot_init(shape):
4346
return tf.random_normal(shape=shape, stddev=1. / tf.sqrt(shape[0] / 2.))
4447

@@ -61,7 +64,7 @@ def glorot_init(shape):
6164
# Building the encoder
6265
input_image = tf.placeholder(tf.float32, shape=[None, image_dim])
6366
encoder = tf.matmul(input_image, weights['encoder_h1']) + biases['encoder_b1']
64-
encoder = tf.nn.relu(encoder)
67+
encoder = tf.nn.tanh(encoder)
6568
z_mean = tf.matmul(encoder, weights['z_mean']) + biases['z_mean']
6669
z_std = tf.matmul(encoder, weights['z_std']) + biases['z_std']
6770

@@ -72,7 +75,7 @@ def glorot_init(shape):
7275

7376
# Building the decoder (with scope to re-use these layers later)
7477
decoder = tf.matmul(z, weights['decoder_h1']) + biases['decoder_b1']
75-
decoder = tf.nn.relu(decoder)
78+
decoder = tf.nn.tanh(decoder)
7679
decoder = tf.matmul(decoder, weights['decoder_out']) + biases['decoder_out']
7780
decoder = tf.nn.sigmoid(decoder)
7881

@@ -99,7 +102,7 @@ def vae_loss(x_reconstructed, x_true):
99102
sess.run(init)
100103

101104
# Training
102-
for i in range(1, n_steps+1):
105+
for i in range(1, num_steps+1):
103106
# Prepare Data
104107
# Get the next batch of MNIST data (only images are needed, not labels)
105108
batch_x, _ = mnist.train.next_batch(batch_size)
@@ -115,24 +118,24 @@ def vae_loss(x_reconstructed, x_true):
115118
noise_input = tf.placeholder(tf.float32, shape=[None, latent_dim])
116119
# Rebuild the decoder to create image from noise
117120
decoder = tf.matmul(noise_input, weights['decoder_h1']) + biases['decoder_b1']
118-
decoder = tf.nn.relu(decoder)
121+
decoder = tf.nn.tanh(decoder)
119122
decoder = tf.matmul(decoder, weights['decoder_out']) + biases['decoder_out']
120123
decoder = tf.nn.sigmoid(decoder)
121124

122125
# Building a manifold of generated digits
123-
n = 15 # Figure row size
124-
figure = np.zeros((28 * n, 28 * n))
125-
# Random normal distributions to feed network with
126-
x_axis = norm.ppf(np.linspace(0., 1., n))
127-
y_axis = norm.ppf(np.linspace(0., 1., n))
128-
129-
for i, x in enumerate(x_axis):
130-
for j, y in enumerate(y_axis):
131-
samples = np.array([[x, y]])
132-
x_reconstructed = sess.run(decoder, feed_dict={noise_input: samples})
133-
digit = np.array(x_reconstructed[0]).reshape(28, 28)
134-
figure[i * 28: (i + 1) * 28, j * 28: (j + 1) * 28] = digit
135-
136-
plt.figure(figsize=(10, 10))
137-
plt.imshow(figure, cmap='Greys_r')
126+
n = 20
127+
x_axis = np.linspace(-3, 3, n)
128+
y_axis = np.linspace(-3, 3, n)
129+
130+
canvas = np.empty((28 * n, 28 * n))
131+
for i, yi in enumerate(x_axis):
132+
for j, xi in enumerate(y_axis):
133+
z_mu = np.array([[xi, yi]] * batch_size)
134+
x_mean = sess.run(decoder, feed_dict={noise_input: z_mu})
135+
canvas[(n - i - 1) * 28:(n - i) * 28, j * 28:(j + 1) * 28] = \
136+
x_mean[0].reshape(28, 28)
137+
138+
plt.figure(figsize=(8, 10))
139+
Xi, Yi = np.meshgrid(x_axis, y_axis)
140+
plt.imshow(canvas, origin="upper", cmap="gray")
138141
plt.show()

0 commit comments

Comments
 (0)