java plt_matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解
學習python的道路是漫長的,今天又遇到一個問題,所以想寫下來自己的理解方便以后查看。
在使用matplotlib的過程中,常常會需要畫很多圖,但是好像并不能同時展示許多圖。這是因為python可視化庫matplotlib的顯示模式默認為阻塞(block)模式。什么是阻塞模式那?我的理解就是在plt.show()之后,程序會暫停到那兒,并不會繼續執行下去。如果需要繼續執行程序,就要關閉圖片。那如何展示動態圖或多個窗口呢?這就要使用plt.ion()這個函數,使matplotlib的顯示模式轉換為交互(interactive)模式。即使在腳本中遇到plt.show(),代碼還是會繼續執行。下面這段代碼是展示兩個不同的窗口:
import matplotlib.pyplot as plt
plt.ion() # 打開交互模式
# 同時打開兩個窗口顯示圖片
plt.figure() #圖片一
plt.imshow(i1)
plt.figure() #圖片二
plt.imshow(i2)
# 顯示前關掉交互模式
plt.ioff()
plt.show()
在plt.show()之前一定不要忘了加plt.ioff(),如果不加,界面會一閃而過,并不會停留。那么動態圖像是如何畫出來的,請看下面這段代碼,具體的解釋就不在這里闡述了,以后有時間再更新:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs,in_size,out_size,activation_funiction=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_funiction is None:
outputs = Wx_plus_b
else:
outputs = activation_funiction(Wx_plus_b)
return outputs
x_data = np.linspace(-1,1,300)[:,np.newaxis]
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])
#add hidden layer
l1 = add_layer(xs,1,10,activation_funiction=tf.nn.relu)
#add output layer
prediction = add_layer(l1,10,1,activation_funiction=None)
#the error between prediction and real data
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.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion() #將畫圖模式改為交互模式
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50 ==0:
plt.pause(0.1)
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)
print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
plt.ioff()
plt.show()
上面這段代碼執行之后就會看到一條曲線在動態的擬合數據,直到訓練結束。
下面就來講講matplotlib這兩種模式具體的區別
在交互模式下:
1、plt.plot(x)或plt.imshow(x)是直接出圖像,不需要plt.show()
2、如果在腳本中使用ion()命令開啟了交互模式,沒有使用ioff()關閉的話,則圖像會一閃而過,并不會常留。要想防止這種情況,需要在plt.show()之前加上ioff()命令。
在阻塞模式下:
1、打開一個窗口以后必須關掉才能打開下一個新的窗口。這種情況下,默認是不能像Matlab一樣同時開很多窗口進行對比的。
2、plt.plot(x)或plt.imshow(x)是直接出圖像,需要plt.show()后才能顯示圖像js
總結
以上是生活随笔為你收集整理的java plt_matplotlib 画动态图以及plt.ion()和plt.ioff()的使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java jdbctemplate赋值_
- 下一篇: java e.getmessage()