Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.preprocessing import MinMaxScaler
  4.  
  5. class Mlp(object):
  6.  
  7. def __init__(self, n_input, h_size, n_layers = 1, act = tf.nn.relu, lr = 0.01):
  8.  
  9. self.x = tf.placeholder('float',[None, n_input] )
  10. self.y = tf.placeholder('float', [None, 1])
  11.  
  12. output = self.x
  13.  
  14. w,b = self.init_variables(n_input, n_layers, h_size)
  15.  
  16. for layer in np.arange(n_layers):
  17. output = act(tf.add(tf.matmul(output, w[layer]), b[layer]))
  18.  
  19. self.loss = tf.reduce_mean((output - self.y)**2)
  20. self.train_step = tf.train.AdamOptimizer(learning_rate=lr).minimize(self.loss)
  21.  
  22. @staticmethod
  23. def init_variables(n_input, h_size, n_layers):
  24.  
  25. w,b = [],[]
  26.  
  27. w.append(tf.Variable(tf.random_normal([n_input, h_size])))
  28. b.append(tf.Variable(tf.random_normal([h_size])))
  29.  
  30. for _ in np.arange(n_layers):
  31. w.append(tf.Variable(tf.random_normal([h_size, h_size])))
  32. b.append(tf.Variable(tf.random_normal([h_size])))
  33.  
  34. w.append(tf.Variable(tf.random_normal([h_size, 1])))
  35. b.append(tf.Variable(tf.random_normal([1])))
  36. return w, b
  37.  
  38. # true function
  39. X = np.linspace(start= -1, stop = 1, num=2*60000)
  40. X = np.reshape(X, (-1, 2))
  41. y = (X[:,0] + X[:,1])
  42. dataset = np.column_stack((X, y))
  43.  
  44.  
  45. # params
  46. n_layers = 1
  47. h_size = 200
  48.  
  49. lr = 0.1
  50. batch_size = 100
  51. eps = 0.05
  52.  
  53.  
  54. mlp = Mlp(n_input=2, n_layers = n_layers, h_size = h_size, act = tf.nn.relu, lr=lr)
  55. sess = tf.Session()
  56. sess.run(tf.global_variables_initializer())
  57.  
  58.  
  59.  
  60. stop = False
  61. step = 0
  62. idx = np.arange(len(dataset))
  63.  
  64. while not stop:
  65. sample_idx = np.random.choice(idx, batch_size)
  66. feed_dict = {
  67. mlp.x: dataset[sample_idx][:,:2],
  68. mlp.y: np.reshape(dataset[sample_idx][:, 2], (-1,1))
  69. }
  70. _, loss = sess.run([mlp.train_step, mlp.loss], feed_dict =feed_dict)
  71. step += 1
  72. if step % 100 == 0:
  73. print(loss)
  74. if loss < eps:
  75. stop = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement