[DL] Build simple model based on Tensorflow
本篇文章是從莫烦的學習影片學習的,主要是教學我們如何建置一個簡單的學習網絡。
以下的程式,主要是運用此方程式 y=Wx+b,
已知變數x,想利用兩個變數 W(weights),b(biases) 去算出我的們期望值y,
並另用SGD去降低loss值,
算出最能接近期望值y時的 W(weights)與b(biases)
以下程式:
# coding=utf-8 import tensorflow as tf import numpy as np # creat data, random value between 0 and 1 x_data = np.random.rand(100).astype(np.float32) # define the learn value # to learn value: Weight:0.1 biases:0.3 # y_data= 真實值 y_data = x_data*0.1+0.3 ### creat tensorflow structure start ### # define the range and initial weights Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) biases = tf.Variable(tf.zeros([1])) # 給定 tensorflow 學習的函數 # y = 預值測 y = Weights*x_data + biases # build loss function loss = tf.reduce_mean(tf.square(y-y_data)) # select optimal methods to reduce loss and learning rate is always less than 1 # Define learning rate=0.5 optimizer = tf.train.GradientDescentOptimizer(0.5) #Optimal the loss value to small ,the best value is 0 train = optimizer.minimize(loss) #Initial all variables init = tf.initialize_all_variables() ### creat tensorflow structure end ### #-------------start to train ---------------# # build sess sess = tf.Session() # To inital see is very important sess.run(init) for step in range(201): sess.run(train) if step % 20 ==0: print(step,sess.run(Weights),sess.run(biases))執行結果:
參考影片:
留言
張貼留言