【python】matplotlib动态显示详解
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 |
2 | 0.58 |
3 | 1.04 |
4 | 1.55 |
5 | 2.15 |
6 | 2.62 |
7 | 2.71 |
8 | 2.73 |
9 | 3.03 |
10 | 3.14 |
11 | 3.58 |
12 | 3.66 |
13 | 3.81 |
14 | 3.83 |
15 | 4.39 |
16 | 4.44 |
17 | 4.6 |
18 | 5.39 |
19 | 5.54 |
20 | 5.76 |
通过一个简单的三层神经网络训练一个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