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函数的数据:
通过一个简单的三层神经网络训练一个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,其参数如下表所示:
信息展示模式,0或1
(Epoch 00001: saving model to ...)
# 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动态显示详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)