欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python使用Matplotlib和Imagemagick实现感知器算法可视化与GIF导出

程序员文章站 2022-03-24 18:27:45
...

首先这类教程网上有很多基本的功能都可以实现,

1,安装ImageMagick

ImageMagick是一个类似于编码器的工具,下载地址:http://www.imagemagick.org/script/binary-releases.php 


2,   安装 PythonMagick,是ImageMagick的python开发包。



3,安装FFmpeg

下载请到官网下载相应版本   的官方网址是 http://ffmpeg.mplayerhq.hu/。

安装之后配置好环境变量





参照http://blog.csdn.net/yjpeng125/article/details/70245685的代码    虽然遇到很多坑  最后还是实现了gif导出

import copy
from matplotlib import pyplot as plt
from matplotlib import animation
plt.rcParams ['animation.ffmpeg_path'] = r'C:\ffmpeg\bin\ffmpeg.exe'
 
training_set = [[(3, 3), 1], [(4, 3), 1], [(1, 1), -1]]
w = [0, 0]
b = 0
history = []
 
 
def update(item):
# 更新权重
    global w, b, history
    w[0] += 1 * item[1] * item[0][0]
    w[1] += 1 * item[1] * item[0][1]
    b += 1 * item[1]
    print(w, b)
    history.append([copy.copy(w), b])
    # you can uncomment this line to check the process of stochastic gradient descent
 
 
def cal(item):
    """
    calculate the functional distance between 'item' an the dicision surface. output yi(w*xi+b).
    :param item:
    :return:
    """
    res = 0
    for i in range(len(item[0])):
        res += item[0][i] * w[i]
    res += b
    res *= item[1]
    return res
 
 
def check():
    """
    check if the hyperplane can classify the examples correctly
    :return: true if it can
    """
    flag = 0
    for item in training_set:
        if cal(item) <= 0:
            flag = True
            update(item)
    # draw a graph to show the process
    if not flag:
        print("RESULT: w: " + str(w) + " b: " + str(b))
    return  flag
 
 
if __name__ == "__main__":
    for i in range(1000):
        if not check(): break
 
    # first set up the figure, the axis, and the plot element we want to animate
    fig = plt.figure()
    ax = plt.axes()
    line, = ax.plot([], [], 'g', lw=3)
    label = ax.text(0,1,'')
   #label = ax.text(([]),([]),'', fontsize=16)
 
    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        x, y, x_, y_ = [], [], [], []
        for p in training_set:
            if p[1] > 0:
                x.append(p[0][0])
                y.append(p[0][1])
            else:
                x_.append(p[0][0])
                y_.append(p[0][1])
 
        plt.plot(x, y, 'bo', x_, y_, 'rx')
        plt.axis([-6, 6, -6, 6])
        plt.grid(True)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.title('Perceptron Algorithm (Lizheng)')
        return line, label
 
    # animation function.  this is called sequentially
    def animate(i):
        global history, ax, line, label
 
        w = history[i][0]
        b = history[i][1]
        if w[1] == 0: return line, label
        x1 = -7
        y1 = -(b + w[0] * x1) / w[1]
        x2 = 7
        y2 = -(b + w[0] * x2) / w[1]
        line.set_data([x1, x2], [y1, y2])
        x1 = 0
        y1 = -(b + w[0] * x1) / w[1]
        label.set_text(history[i])
        label.set_position([x1, y1])
        return line, label
  1. anim.save('perceptron.gif', fps=2, writer='imagemagick')
# call the animator. blit=true means only re-draw the parts that have changed. print (history) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(history), interval=1000, repeat=True, blit=True) plt.show() 上面的代码是在前人的基础上做了修改后可以正常跑通的

提示

坑的位置

--------------------------1--------------------------------------------------------------------------------------------------------------------------------------------------------------------

Python使用Matplotlib和Imagemagick实现感知器算法可视化与GIF导出

这个地方如果大家没有更改的话 跑起来会有提示Python使用Matplotlib和Imagemagick实现感知器算法可视化与GIF导出

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2