今天就跟大家聊聊有關plt.ion()與plt.ioff()怎么在matplotlib中使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
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()后才能顯示圖像
看完上述內容,你們對plt.ion()與plt.ioff()怎么在matplotlib中使用有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。