Advertisement
Star12465

TensorFlow Example.1

Dec 11th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #-*- coding: utf-8 -*- 
  2. #引用必要函數
  3. import tensorflow as tf
  4. import numpy as np
  5.  
  6. # creat data
  7. #創造 亂數100個亂數 值介於0~1之間
  8. x_data = np.random.rand(100).astype(np.float32)
  9.  
  10. #訂出要學習的函數  這裡要學的是 weight:0.1  biases:0.3
  11. y_data = x_data*0.1+0.3
  12.  
  13. ###creat tensorflow structure start###
  14. #定立 weights 的 範圍 和初始化
  15. Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
  16. biases = tf.Variable(tf.zeros([1]))
  17.  
  18. #定立 給 tensorflow 學習的函數
  19. y = Weights*x_data + biases
  20.  
  21. #建立 loss 規則
  22. loss = tf.reduce_mean(tf.square(y-y_data))
  23.  
  24. #選擇學習機制
  25. optimizer = tf.train.GradientDescentOptimizer(0.5)  #learning rate
  26.  
  27. #像tensorflow 說 訓練規則就是把 loss 減到最小 最好是0
  28. train = optimizer.minimize(loss)
  29.  
  30. #初始化所有變數
  31. init = tf.initialize_all_variables()
  32.  
  33. ###creat tensorflow structure end###
  34. #上面都是建立規則
  35. #*****************************************************開始訓練
  36. #建立sess
  37. sess = tf.Session()
  38.  
  39. #記得初始化
  40. sess.run(init)     #Very important
  41.  
  42. """
  43. 跑 for 迴圈 更新wight201次
  44. 然後每訓練20次 印出一次weight
  45. """
  46. for step in range(201):
  47.     sess.run(train)
  48.     if step % 20 ==0:
  49.         print(step,sess.run(Weights),sess.run(biases))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement