您好,登錄后才能下訂單哦!
1.matplotlib動態繪圖
python在繪圖的時候,需要開啟 interactive mode。核心代碼如下:
plt.ion(); #開啟interactive mode 成功的關鍵函數 fig = plt.figure(1); for i in range(100): filepath="E:/Model/weights-improvement-" + str(i + 1) + ".hdf5"; model.load_weights(filepath); #測試數據 x_new = np.linspace(low, up, 1000); y_new = getfit(model,x_new); # 顯示數據 plt.clf(); plt.plot(x,y); plt.scatter(x_sample, y_sample); plt.plot(x_new,y_new); ffpath = "E:/imgs/" + str(i) + ".jpg"; plt.savefig(ffpath); plt.pause(0.01) # 暫停0.01秒 ani = animation.FuncAnimation(plt.figure(2), update,range(100),init_func=init, interval=500); ani.save("E:/test.gif",writer='pillow'); plt.ioff() # 關閉交互模式
2.實例
已知下面采樣自Sin函數的數據:
x | y | |
1 | 0.093 | -0.81 |
2 | 0.58 | -0.45 |
3 | 1.04 | -0.007 |
4 | 1.55 | 0.48 |
5 | 2.15 | 0.89 |
6 | 2.62 | 0.997 |
7 | 2.71 | 0.995 |
8 | 2.73 | 0.993 |
9 | 3.03 | 0.916 |
10 | 3.14 | 0.86 |
11 | 3.58 | 0.57 |
12 | 3.66 | 0.504 |
13 | 3.81 | 0.369 |
14 | 3.83 | 0.35 |
15 | 4.39 | -0.199 |
16 | 4.44 | -0.248 |
17 | 4.6 | -0.399 |
18 | 5.39 | -0.932 |
19 | 5.54 | -0.975 |
20 | 5.76 | -0.999 |
通過一個簡單的三層神經網絡訓練一個Sin函數的擬合器,并可視化模型訓練過程的擬合曲線。
2.1 網絡訓練實現
主要做的事情是定義一個三層的神經網絡,輸入層節點數為1,隱藏層節點數為10,輸出層節點數為1。
import math; import random; from matplotlib import pyplot as plt from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import Adam import numpy as np from keras.callbacks import ModelCheckpoint import os #采樣函數 def sample(low, up, num): data = []; for i in range(num): #采樣 tmp = random.uniform(low, up); data.append(tmp); data.sort(); return data; #sin函數 def func(x): y = []; for i in range(len(x)): tmp = math.sin(x[i] - math.pi/3); y.append(tmp); return y; #獲取模型擬合結果 def getfit(model,x): y = []; for i in range(len(x)): tmp = model.predict([x[i]], 10); y.append(tmp[0][0]); return y; #刪除同一目錄下的所有文件 def del_file(path): ls = os.listdir(path) for i in ls: c_path = os.path.join(path, i) if os.path.isdir(c_path): del_file(c_path) else: os.remove(c_path) if __name__ == '__main__': path = "E:/Model/"; del_file(path); low = 0; up = 2 * math.pi; x = np.linspace(low, up, 1000); y = func(x); # 數據采樣 # x_sample = sample(low,up,20); x_sample = [0.09326442022999694, 0.5812590520508311, 1.040490143783586, 1.5504427746047338, 2.1589557183817036, 2.6235357787018407, 2.712578091093361, 2.7379109336528167, 3.0339662651841186, 3.147676812083248, 3.58596337171837, 3.6621496731124314, 3.81130899864203, 3.833092859928872, 4.396611340802901, 4.4481080339256875, 4.609657879057151, 5.399731063412583, 5.54299720786794, 5.764084730699906]; y_sample = func(x_sample); # callback filepath="E:/Model/weights-improvement-{epoch:00d}.hdf5"; checkpoint= ModelCheckpoint(filepath, verbose=1, save_best_only=False, mode='max'); callbacks_list= [checkpoint]; # 建立順序神經網絡層次模型 model = Sequential(); model.add(Dense(10, input_dim=1, init='uniform', activation='relu')); model.add(Dense(1, init='uniform', activation='tanh')); adam = Adam(lr = 0.05); model.compile(loss='mean_squared_error', optimizer=adam, metrics=['accuracy']); model.fit(x_sample, y_sample, nb_epoch=1000, batch_size=20,callbacks=callbacks_list); #測試數據 x_new = np.linspace(low, up, 1000); y_new = getfit(model,x_new); # 數據可視化 plt.plot(x,y); plt.scatter(x_sample, y_sample); plt.plot(x_new,y_new); plt.show();
2.2 模型保存
在神經網絡訓練的過程中,有一個非常重要的操作,就是將訓練過程中模型的參數保存到本地,這是后面擬合過程可視化的基礎。訓練過程中保存的模型文件,如下圖所示。
模型保存的關鍵在于fit函數中callback函數的設置,注意到,下面的代碼,每次迭代,算法都會執行callbacks函數指定的函數列表中的方法。這里,我們的回調函數設置為ModelCheckpoint,其參數如下表所示:
參數 | 含義 |
filename | 字符串,保存模型的路徑 |
verbose |
信息展示模式,0或1 (Epoch 00001: saving model to ...) |
mode | ‘auto',‘min',‘max' |
monitor | 需要監視的值 |
save_best_only | 當設置為True時,監測值有改進時才會保存當前的模型。在save_best_only=True時決定性能最佳模型的評判準則,例如,當監測值為val_acc時,模式應為max,當監測值為val_loss時,模式應為min。在auto模式下,評價準則由被監測值的名字自動推斷 |
save_weights_only | 若設置為True,則只保存模型權重,否則將保存整個模型(包括模型結構,配置信息等) |
period | CheckPoint之間的間隔的epoch數 |
# callback filepath="E:/Model/weights-improvement-{epoch:00d}.hdf5"; checkpoint= ModelCheckpoint(filepath, verbose=1, save_best_only=False, mode='max'); callbacks_list= [checkpoint]; # 建立順序神經網絡層次模型 model = Sequential(); model.add(Dense(10, input_dim=1, init='uniform', activation='relu')); model.add(Dense(1, init='uniform', activation='tanh')); adam = Adam(lr = 0.05); model.compile(loss='mean_squared_error', optimizer=adam, metrics=['accuracy']); model.fit(x_sample, y_sample, nb_epoch=1000, batch_size=20,callbacks=callbacks_list);
2.3 擬合過程可視化實現
利用上述保存的模型,我們就可以通過matplotlib實時地顯示擬合過程。
import math; import random; from matplotlib import pyplot as plt from keras.models import Sequential from keras.layers.core import Dense import numpy as np import matplotlib.animation as animation from PIL import Image #定義kdd99數據預處理函數 def sample(low, up, num): data = []; for i in range(num): #采樣 tmp = random.uniform(low, up); data.append(tmp); data.sort(); return data; def func(x): y = []; for i in range(len(x)): tmp = math.sin(x[i] - math.pi/3); y.append(tmp); return y; def getfit(model,x): y = []; for i in range(len(x)): tmp = model.predict([x[i]], 10); y.append(tmp[0][0]); return y; def init(): fpath = "E:/imgs/0.jpg"; img = Image.open(fpath); plt.axis('off') # 關掉坐標軸為 off return plt.imshow(img); def update(i): fpath = "E:/imgs/" + str(i) + ".jpg"; img = Image.open(fpath); plt.axis('off') # 關掉坐標軸為 off return plt.imshow(img); if __name__ == '__main__': low = 0; up = 2 * math.pi; x = np.linspace(low, up, 1000); y = func(x); # 數據采樣 # x_sample = sample(low,up,20); x_sample = [0.09326442022999694, 0.5812590520508311, 1.040490143783586, 1.5504427746047338, 2.1589557183817036, 2.6235357787018407, 2.712578091093361, 2.7379109336528167, 3.0339662651841186, 3.147676812083248, 3.58596337171837, 3.6621496731124314, 3.81130899864203, 3.833092859928872, 4.396611340802901, 4.4481080339256875, 4.609657879057151, 5.399731063412583, 5.54299720786794, 5.764084730699906]; y_sample = func(x_sample); # 建立順序神經網絡層次模型 model = Sequential(); model.add(Dense(10, input_dim=1, init='uniform', activation='relu')); model.add(Dense(1, init='uniform', activation='tanh')); plt.ion(); #開啟interactive mode 成功的關鍵函數 fig = plt.figure(1); for i in range(100): filepath="E:/Model/weights-improvement-" + str(i + 1) + ".hdf5"; model.load_weights(filepath); #測試數據 x_new = np.linspace(low, up, 1000); y_new = getfit(model,x_new); # 顯示數據 plt.clf(); plt.plot(x,y); plt.scatter(x_sample, y_sample); plt.plot(x_new,y_new); ffpath = "E:/imgs/" + str(i) + ".jpg"; plt.savefig(ffpath); plt.pause(0.01) # 暫停0.01秒 ani = animation.FuncAnimation(plt.figure(2), update,range(100),init_func=init, interval=500); ani.save("E:/test.gif",writer='pillow'); plt.ioff()
以上所述是小編給大家介紹的matplotlib動態顯示詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。