机器学习需要使用python实现相应的算法,因此学习了Matplotlib中的画图。
当然为了能显示机器学习中每次迭代的效果与收敛速度,需要画出动态图形。
下面给出两个例子,分别可以画出动态条形图和动态折线图(使用两种不同的方法)。
注意要使用到plt.pause(time)函数。
基本原理是将数据放入数组,然后每次往数组里面增加一个数,清除之前的图,重新画出图像。
代码:
Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
y1 = []
for i in range(50):
y1.append(i) # 每迭代一次,将i放入y1中画出来
ax.cla() # 清除键
ax.bar(y1, label='test', height=y1, width=0.3)
ax.legend()
plt.pause(0.1)
效果:
基本原理是使用一个长度为2的数组,每次替换数据并在原始图像后追加。
代码:
Python
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0, 100, 0, 1])
plt.ion()
xs = [0, 0]
ys = [1, 1]
for i in range(100):
y = np.random.random()
xs[0] = xs[1]
ys[0] = ys[1]
xs[1] = i
ys[1] = y
plt.plot(xs, ys)
plt.pause(0.1)
效果:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有