1. 程式人生 > >莫煩python|Tensorflow筆記--tf10、tf11

莫煩python|Tensorflow筆記--tf10、tf11

為神經網路新增一個神經層

import tensorflow as tf

# 新增一個神經層,定義新增神經層的函式
def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))  # 定義權重  隨機變數矩陣
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)     # 初始值一般不為0,所以加個0.1
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

構造一個簡單的神經網路來預測y=x^2

import tensorflow as tf
import numpy as np
# 新增一個神經層,定義新增神經層的函式
def add_layer(inputs, in_size, out_size, activation_function=None):
    # add one more layer and return the output of this layer
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))   # in_sized代表行數
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases  # Wx_plus_b 代表wx+b
    if activation_function is None:  # 如果沒有激勵函式,即為線性關係,那麼直接輸出,不需要激勵函式(非線性函式)
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)  # 把這個值傳進去
    return outputs

# Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis]      # 輸入,np.float32改變陣列的長度顯示,linspace建立一個從-1到1的等差數列,預設為50個數,這裡規定了要生成300個數,並且使用[:, np.newaxis]將陣列轉換為列向量,[np.newaxis,:]可轉換為行向量
noise = np.random.normal(0, 0.05, x_data.shape)     # 生成一個均值/中心為0,標準差/寬度為0.05的正太分佈作為噪點/干擾點,它的格式為x_data,使得我們想要預測的函式更加接近實際情況;astype轉換資料型別格式為float32
y_data = np.square(x_data) - 0.5 + noise      # x的平方減去一個任意值再加上噪點

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])       #  佔位符,儲存資料的利器,float32資料型別,[None,1]表示列為1,行不定的列向量;xs表示x_Session,因為placeholder是與Session一起用的,它在使用的時候和前面的variable不同的是在session執行階段,需要給placeholder提供資料,利用feed_dict的字典結構給placeholdr變數“喂資料”;placeholder的語法:tf.placeholder(dtype, shape=[None,None] [, name=None])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  # 建立一個隱藏層l1,輸入為xs,輸入的層數/神經元的個數1=輸入層,輸出的層數10=隱藏層中神經元的個數
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)   #  預測值;定義輸出層,輸入為l1=前一層隱藏層的輸出,輸入的層數為10=隱藏層神經元的個數,輸出的層數為1=輸出一般只有1層

# the error between prediction and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),  # 計算預測值prediction與真實值ys的誤差:所有的平方差相加再求平均;reduction_indices = [1]表示相加的方法,[1]表示行求和,[0]表示列求和,具體解釋見下文
                     reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  # 機器要學習的內容,使用優化器提升準確率,學習率為0.1<1,表示以0.1的效率來最小化誤差loss

# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()  # 使用變數,就要對其初始化
sess = tf.Session()  # 定義Session,並使用Session來初始化步驟
sess.run(init)

for i in range(1000):   #  訓練1000次
    # training
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})   # 給placeholder喂資料,把x_data賦值給xs
    if i % 50 == 0:   #  每50步輸出一次機器學習的誤差
        # to see the step improvement
        print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))

結果

0.435219
0.0223464
0.0112225
0.00867539
0.00786375
0.00735494
0.00683158
0.00629177
0.00583583
0.00542399
0.00509898
0.00481139
0.00456206
0.00434052
0.00416177
0.00401051
0.00387347
0.00374463
0.00363119
0.00353645