Advertisement
Guest User

ลองใช้ Tensorflow ทำ Linear Regression

a guest
Apr 14th, 2017
685
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. import numpy as np
  2. import tensorflow as tf
  3.  
  4. # ประกาศ parameter ที่ต้องการทราบก่อน
  5. W = tf.Variable([.3], tf.float32)
  6. b = tf.Variable([-.3], tf.float32)
  7. # ตรงนี้เป็น model input output
  8. x = tf.placeholder(tf.float32)
  9. linear_model = W * x + b
  10. y = tf.placeholder(tf.float32)
  11. # loss เป็นตัวบอกว่า model ที่ได้ใน input เดียวกัน output มันคลาดเคลื่อนไปจาก datasets เท่าไร
  12. loss = tf.reduce_sum(tf.square(linear_model - y))
  13. # optimizer นี่ตามชื่อเลยครับ
  14. optimizer = tf.train.GradientDescentOptimizer(0.01)
  15. train = optimizer.minimize(loss) #ตรงนี้จะพยายามลด Loss ให้น้อยที่สุด
  16. # datasets ของเรา
  17. x_train = [1,2,3,4]
  18. y_train = [0,-1,-2,-3]
  19. # อันนี้เป็นขั้นตอน training
  20. init = tf.global_variables_initializer()
  21. sess = tf.Session()
  22. sess.run(init)
  23. for i in range(1000):
  24.   sess.run(train, {x:x_train, y:y_train})
  25.  
  26. # พอ train เสร็จเราก็จะมาดูผลที่ได้
  27. curr_W, curr_b, curr_loss  = sess.run([W, b, loss], {x:x_train, y:y_train})
  28. print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement