1、安裝matplotlib [Python中畫圖的工具包] ,否則會報錯。
Python庫導入錯誤:ImportError: No module named matplotlib.pyplot
補救:
2、在上一篇代碼的基礎上添加可視化代碼。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt #Python中畫圖的工具包
#添加神經層的函數
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 #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] #300行1列
noise = np.random.normal(0,0.05,x_data.shape)
y_data = np.square(x_data) -0.5 + noise
xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
l1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction = add_layer(l1,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)
# fig = plt.figure() #首先生成一個圖片框
# ax = fig.add_subplot(1,1,1) #要做一個連續性的plot畫圖需要用這個 #(1,1,1):編號
# ax.scatter(x_data,y_data) #畫散點圖 #用點的形式plot上來
# #plt.ion() #讓程序plot後不暫停
# #plt.show() #打印 真實數據 打印完整個程序暫停了
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
for i in range(1000):
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
prediction_value = sess.run(prediction,feed_dict={xs:x_data})
lines = ax.plot(x_data,prediction_value,'r-',lw=5)
plt.pause(0.1)
# if i %50 == 0:
#print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
# try:
# ax.lines.remove(lines[0]) #抹去lines的第一條線段 (本來就一條,所以就是這條)
# except Exception:
# pass #什麼都不做
# prediction_value = sess.run(prediction,feed_dict={xs:x_data})
# lines = ax.plot(x_data,prediction_value,'r-',lw=5) #用曲線形式,把prediction的值plot上去 紅線,線寬爲5
# #如果想連續plot的話,plot出的每條線要先抹去,再plot另外一條線。否則就是疊加。
# plt.pause(0.1) #暫停0.1秒
效果:動態的,這裏僅爲截圖
前提:Python版本需要>3.5,否則應當去掉 plt.ion(),並將plt.show()改爲plt.show(block=False)。否則畫完散點圖後程序暫停,無法繼續出現折線圖。
3、思路:
1、導入matplotlib包
2、真實數據用散點圖表示。(x_data,y_data)
3、預測數據用折線圖表示。(x_data,prediction_value)
注意:prediction是個op,prediction_value是個value
4、折線效果每0.1秒擦除並重新畫。
4、踩坑:
我使用jupyter編寫和運行python代碼,jupyter默認對動態圖無法顯示,只能顯示靜態效果。
我百度到的各種方法均效果不佳,最終將代碼粘貼在cmd命令行上,才能通過彈窗實現動態效果。
ps:
想換個寫python的軟件了,畢竟後面要寫大數據層次的深度學習,怕jupyter帶不起來。
大家有沒有好用的軟件推薦一下呀(づ ̄3 ̄)づ╭❤~