baotrung217

tf-linear-regression

Dec 5th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. import tensorflow as tf
  2.  
  3. # initialize variables/model parameters
  4. W = tf.Variable(tf.zeros([2,1]), name="weights")
  5. b = tf.Variable(0., name="bias")
  6.  
  7. # define the training loop operations
  8. def inference(X):
  9.     # compute inference model over data X and return the result
  10.     # pass
  11.     return tf.matmul(X, W) + b
  12.  
  13. def loss(X, Y):
  14.     # compute loss over training data X and expected output Y
  15.     # pass
  16.     Y_predicted = inference(X)
  17.     return tf.reduce_sum(tf.squared_difference(Y, Y_predicted))
  18.  
  19. def inputs():
  20.     # read/generate input training data X and expected output Y
  21.     # pass
  22.     weight_age = [[84,46], [73,20], [65,52], [70,30], [76,57], [69,25], [63,28], [72,36],   [79,57], [75,44], [27,24], [89,31], [65,52], [57,23], [59,60], [69,48], [60,34], [79,51], [75,50], [82,34], [59,46], [67,23], [85,37], [55,40]]
  23.     blood_fat_content = [354, 190, 405, 263, 451, 302, 288, 385, 402, 365, 209, 290, 346,   254, 395, 434, 220, 374, 308, 220, 311, 181, 274, 303]
  24.     return tf.to_float(weight_age), tf.to_float(blood_fat_content)
  25.  
  26. def train(total_loss):
  27.     # train/adjust model parameters according to computed total loss
  28.     # pass
  29.     learning_rate = 0.0000001
  30.     return tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)
  31.  
  32. def evaluate(sess, X, Y):
  33.     # evaluate the resulting trained model
  34.     # pass
  35.     print(sess.run(inference([[80.,25.]]))) #~303
  36.     print(sess.run(inference([[63.,30.]]))) #~256
  37.  
  38. # launch the graph in a session, setup boilerplate
  39. with tf.Session() as sess:
  40.  
  41.     tf.initialize_all_variables().run()
  42.  
  43.     X, Y = inputs()
  44.  
  45.     total_loss = loss(X, Y)
  46.     train_op = train(total_loss)
  47.  
  48.     coord = tf.train.Coordinator()
  49.     threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  50.  
  51.     # actual training loop
  52.     training_steps = 1000
  53.     for step in range(training_steps):
  54.         sess.run([train_op])
  55.         # for debugging or learning purposes
  56.         if step%10 == 0:
  57.             print("loss: ", sess.run([total_loss]))
  58.            
  59.     evaluate(sess, X, Y)
  60.     coord.request_stop()
  61.     coord.join(threads)
  62.     sess.close()
Advertisement
Add Comment
Please, Sign In to add comment