In [1]:
import tensorflow as tf
import numpy as np

def rand01(digit):
	# Add some random noise to bits, but keep always between 0 and 1
	s = abs(np.random.normal(0.0, 0.05))
	if digit == 0:
		noise = digit + s
	else:
		noise = digit - s
	return noise

### Training Examples
### All combinations of XOR

X = [[0, 0],[0, 1],[1, 0],[1, 1]]
Y = [[0], [1], [1], [0]]

# Add some random noise to our inputs. Useful if we use the tanh activiation function

add_noise = np.vectorize(rand01)  
X = add_noise(X)
Y = add_noise(Y)

# Neural Network Parameters

N_STEPS = 200000
N_EPOCH = 5000
N_TRAINING = len(X)

N_INPUT_NODES = 2
N_HIDDEN_NODES = 5
N_OUTPUT_NODES  = 1
ACTIVATION = 'tanh' # sigmoid or tanh
COST = 'ACE' # MSE or ACE
LEARNING_RATE = 0.05

if __name__ == '__main__':

	
	### Create placeholders for variables and define Neural Network structure  ###
	### Feed forward 3 layer, Neural Network.                                  ###
	


	x_ = tf.placeholder(tf.float32, shape=[N_TRAINING, N_INPUT_NODES], name="x-input")
	y_ = tf.placeholder(tf.float32, shape=[N_TRAINING, N_OUTPUT_NODES], name="y-input")

	theta1 = tf.Variable(tf.random_uniform([N_INPUT_NODES,N_HIDDEN_NODES], -1, 1), name="theta1")
	theta2 = tf.Variable(tf.random_uniform([N_HIDDEN_NODES,N_OUTPUT_NODES], -1, 1), name="theta2")

	bias1 = tf.Variable(tf.zeros([N_HIDDEN_NODES]), name="bias1")
	bias2 = tf.Variable(tf.zeros([N_OUTPUT_NODES]), name="bias2")


	if ACTIVATION == 'sigmoid':

		### Use a sigmoidal activation function ###

		layer1 = tf.sigmoid(tf.matmul(x_, theta1) + bias1)
		output = tf.sigmoid(tf.matmul(layer1, theta2) + bias2)

	else:
		### Use tanh activation function ###

		layer1 = tf.tanh(tf.matmul(x_, theta1) + bias1)
		output = tf.tanh(tf.matmul(layer1, theta2) + bias2)
	
		output = tf.add(output, 1)
		output = tf.multiply(output, 0.5)

	
	if COST == "MSE":

		# Mean Squared Estimate - the simplist cost function (MSE)

		cost = tf.reduce_mean(tf.square(Y - output)) 
		train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cost)
	
	else:
		# Average Cross Entropy - better behaviour and learning rate

		
		cost = - tf.reduce_mean( (y_ * tf.log(output)) + (1 - y_) * tf.log(1.0 - output)  )
		train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cost)



	init = tf.initialize_all_variables()
	sess = tf.Session()
	sess.run(init)


	for i in range(N_STEPS):
		sess.run(train_step, feed_dict={x_: X, y_: Y})
		if i % N_EPOCH == 0:
			print('Batch ', i)
			print('Inference ', sess.run(output, feed_dict={x_: X, y_: Y}))
			print('Cost ', sess.run(cost, feed_dict={x_: X, y_: Y}))
			#print('op: ', sess.run(output))


WARNING:tensorflow:From /Anaconda/anaconda3/lib/python3.6/site-packages/tensorflow/python/util/tf_should_use.py:170: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
Batch  0
Inference  [[ 0.50639445]
 [ 0.76389694]
 [ 0.28667706]
 [ 0.56264138]]
Cost  0.757263
Batch  5000
Inference  [[ 0.0739235 ]
 [ 0.94382274]
 [ 0.92097163]
 [ 0.05843967]]
Cost  0.24475
Batch  10000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  15000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  20000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  25000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  30000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  35000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  40000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  45000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  50000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  55000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  60000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  65000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  70000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  75000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  80000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  85000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  90000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  95000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  100000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  105000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  110000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  115000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  120000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  125000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  130000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  135000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  140000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  145000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  150000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  155000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  160000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  165000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  170000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  175000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  180000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  185000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  190000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475
Batch  195000
Inference  [[ 0.07392347]
 [ 0.94382274]
 [ 0.92097175]
 [ 0.05843961]]
Cost  0.24475

In [2]:
#!/usr/bin/env PYTHONIOENCODING="utf-8" python
"""
A simple neural network learning the XOR function
"""
import tensorflow as tf
sess = tf.InteractiveSession()

# Desired input output mapping of XOR function:
x_ = [[0, 0], [0, 1], [1, 0], [1, 1]] # input
#labels=[0,      1,      1,      0]   # output =>
expect=[[1,0],  [0,1],  [0,1], [1,0]] # ONE HOT REPRESENTATION! 'class' [1,0]==0 [0,1]==1

# x = tf.Variable(x_)
x = tf.placeholder("float", [None,2]) #  can we feed directly?
y_ = tf.placeholder("float", [None, 2]) # two output classes

number_hidden_nodes = 20 # 20 outputs to create some room for negatives and positives

W = tf.Variable(tf.random_uniform([2, number_hidden_nodes], -.01, .01))
b = tf.Variable(tf.random_uniform([number_hidden_nodes], -.01, .01))
hidden  = tf.nn.relu(tf.matmul(x,W) + b) # first layer.

 # the XOR function is the first nontrivial function, for which a two layer network is needed.
W2 = tf.Variable(tf.random_uniform([number_hidden_nodes,2], -.1, .1))
b2 = tf.Variable(tf.zeros([2]))
hidden2 = tf.matmul(hidden, W2)#+b2

y = tf.nn.softmax(hidden2)


# Define loss and optimizer
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)

# Train
tf.initialize_all_variables().run()
for step in range(1000):
    feed_dict={x: x_, y_:expect } # feed the net with our inputs and desired outputs.
    e,a=sess.run([cross_entropy,train_step],feed_dict)
    if e<1:break # early stopping yay
    print ("step %d : entropy %s" % (step,e)) # error/loss should decrease over time


# Test trained model
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) # argmax along dim-1
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # [True, False, True, True] -> [1,0,1,1] -> 0.75.

print ("accuracy %s"%(accuracy.eval({x: x_, y_: expect})))

learned_output=tf.argmax(y,1)
print (learned_output.eval({x: x_}))


WARNING:tensorflow:From /Anaconda/anaconda3/lib/python3.6/site-packages/tensorflow/python/util/tf_should_use.py:170: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
step 0 : entropy 2.77272
step 1 : entropy 2.77167
step 2 : entropy 2.77156
step 3 : entropy 2.77079
step 4 : entropy 2.77018
step 5 : entropy 2.76979
step 6 : entropy 2.76903
step 7 : entropy 2.76785
step 8 : entropy 2.76743
step 9 : entropy 2.76612
step 10 : entropy 2.76458
step 11 : entropy 2.76355
step 12 : entropy 2.7618
step 13 : entropy 2.75883
step 14 : entropy 2.75736
step 15 : entropy 2.75412
step 16 : entropy 2.74999
step 17 : entropy 2.74687
step 18 : entropy 2.74243
step 19 : entropy 2.73504
step 20 : entropy 2.73068
step 21 : entropy 2.72272
step 22 : entropy 2.71189
step 23 : entropy 2.70349
step 24 : entropy 2.69228
step 25 : entropy 2.67355
step 26 : entropy 2.66172
step 27 : entropy 2.64212
step 28 : entropy 2.61589
step 29 : entropy 2.58609
step 30 : entropy 2.56736
step 31 : entropy 2.52792
step 32 : entropy 2.48509
step 33 : entropy 2.44258
step 34 : entropy 2.41147
step 35 : entropy 2.34175
step 36 : entropy 2.29022
step 37 : entropy 2.23332
step 38 : entropy 2.135
step 39 : entropy 2.11174
step 40 : entropy 2.00596
step 41 : entropy 1.90389
step 42 : entropy 1.84583
step 43 : entropy 1.76251
step 44 : entropy 1.65035
step 45 : entropy 1.57828
step 46 : entropy 1.47246
step 47 : entropy 1.36151
step 48 : entropy 1.29326
step 49 : entropy 1.1913
step 50 : entropy 1.10231
step 51 : entropy 1.00078
accuracy 1.0
[0 1 1 0]

In [ ]: