1. 程式人生 > >tensorflow結果視覺化

tensorflow結果視覺化

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""

# 如何建造神經網路
from __future__ import print_function
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

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)
    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
#聲稱資料
x_data = np.linspace(-1,1,300)[:,np.newaxis]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
#print(x_data)

#利用佔位符定義我們所需的神經網路的輸入。 tf.placeholder()就是代表佔位符,
#這裡的None代表無論輸入有多少都可以,因為輸入只有一個特徵,所以這裡是1。
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
'''
我們就可以開始定義神經層了。 通常神經層都包括輸入層、隱藏層和輸出層。
這裡的輸入層只有一個屬性, 所以我們就只有一個輸入;隱藏層我們可以自己假設,
這裡我們假設隱藏層有10個神經元; 輸出層和輸入層的結構是一樣的,所以我們的輸出層也是隻有一層。
所以,我們構建的是——輸入層1個、隱藏層10個、輸出層1個的神經網路。
'''
#定義隱藏層
layer1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
#定義輸出層|預測 沒有激勵函式
prediction = add_layer(layer1,10,1,activation_function=None)

#求取預測值和真實值的誤差
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
                                    reduction_indices=[1]))
#使用優化器來最小化誤差
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 重要一步,變數初始化
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

#plot the real data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion()  #plt.ion()用於連續顯示
plt.show()


#plot the prediction data
for i in range(3000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if i%50 == 0:
        try: ax.lines.remove(lines[0])
        except Exception:
            pass
        #print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
        prediction_value = sess.run(prediction,feed_dict={xs:x_data,ys:y_data})
        #plot the prediction data
        lines = ax.plot(x_data,prediction_value,'r-',lw=5)
        plt.pause(1) #暫停1秒再繼續