Guest User

Untitled

a guest
Apr 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __author__ = 'maxim'
  4.  
  5. import tensorflow as tf
  6. import numpy as np
  7.  
  8. def random_normal(shape):
  9. return (np.random.random(shape) - 0.5) * 2
  10.  
  11. input_size = 2
  12. hidden_size = 16
  13. output_size = 1
  14.  
  15. x = tf.placeholder(dtype=tf.float32, name="X")
  16. y = tf.placeholder(dtype=tf.float32, name="Y")
  17.  
  18. W1 = tf.Variable(random_normal((input_size, hidden_size)), dtype=tf.float32, name="W1")
  19. W2 = tf.Variable(random_normal((hidden_size, output_size)), dtype=tf.float32, name="W2")
  20.  
  21. b1 = tf.Variable(random_normal(hidden_size), dtype=tf.float32, name="b1")
  22. b2 = tf.Variable(random_normal(output_size), dtype=tf.float32, name="b2")
  23.  
  24. l1 = tf.sigmoid(tf.add(tf.matmul(x, W1), b1), name="l1")
  25. result = tf.sigmoid(tf.add(tf.matmul(l1, W2), b2), name="l2") # Note: works much better without sigmoid
  26.  
  27. r_squared = tf.square(result - y)
  28. loss = tf.reduce_mean(r_squared)
  29.  
  30. optimizer = tf.train.GradientDescentOptimizer(0.1)
  31. train = optimizer.minimize(loss)
  32.  
  33. train_x = np.array([[1, 0], [0, 1], [1, 1], [0, 0]]).reshape((4, 2))
  34. train_y = np.array([1, 1, 0, 0]).reshape((4, 1))
  35.  
  36. with tf.Session() as sess:
  37. sess.run(tf.global_variables_initializer())
  38. for itr in range(10000):
  39. _, loss_val = sess.run([train, loss], {x: train_x, y: train_y})
  40. if itr % 100 == 0:
  41. prediction = sess.run(result, {x: [[1, 0]]})
  42. print('Epoch %d done. Loss=%.6f Prediction=%.6f' % (itr, loss_val, prediction))
Add Comment
Please, Sign In to add comment