Skip to main content
 首页 » 编程设计

python之在 matplotlib 中绘制二维函数

2024年11月01日10zhujiabin

亲爱的程序员和科学 worker :)

我正在使用带有 numpy 和 matplotlib 的 python 来模拟感知器,很自豪地说它工作得很好。

我以前从未见过 python,甚至用得很厉害,因为我听说 matplotlib 提供了惊人的图形可视化功能。

使用下面的函数我得到一个二维数组,如下所示: [[aplha_1, 900], [alpha_2], 600, .., [alpha_99, 900]

所以我得到了这个二维数组,并且很想编写一个函数来分析收敛性。

我正在寻找可以轻松直观地(现在没有时间花 5 个小时研究一个全新的库)绘制如下草图的函数:

def get_convergence_for_alpha(self, _alpha): 
    epochs = [] 
    for i in range(0, 5): 
        epochs.append(self.perceptron_algorithm()) 
        self.weights = self.generate_weights() 
 
    avg = sum(epochs, 0) / len(epochs) 
    res = [_alpha, avg] 
    return res 

这就是整个生成函数。

def alpha_convergence_function(self): 
    res = [] 
    for i in range(1, 100): 
        res.append(self.get_convergence_for_alpha(i / 100)) 
 
    return res 

这很容易做到吗?

请您参考如下方法:

您可以将嵌套列表转换为 2d numpy 数组,然后使用切片来获取 alpha 和纪元计数(就像在 matlab 中一样)。

import numpy as np 
import matplotlib.pyplot as plt 
 
# code to simulate the perceptron goes here... 
 
res = your_object.alpha_convergence_function() 
res = np.asarray(res) 
 
print('array size:', res.shape) 
 
plt.xkcd()   # so you get the sketchy look :) 
 
# first column -> x-axis, second column -> y-axis 
plt.plot(res[:,0], res[:,1]) 
plt.show() 

如果您实际上不希望绘图看起来像草图,请删除 plt.xkcd() 行...