在matplotlib中绘制二维函数

2 投票
1 回答
1474 浏览
提问于 2025-04-17 21:57

亲爱的程序员朋友们和科学爱好者们 :)

我正在用Python配合numpy和matplotlib来模拟一个感知器,骄傲地说它运行得相当不错。

虽然我以前从没接触过Python,但我听说matplotlib能提供很棒的图形可视化功能,所以我还是决定试试。

通过下面的函数,我得到了一个二维数组,长得像这样:

[[aplha_1, 900], [alpha_2, 600], .., [alpha_99, 900]]

所以我得到了这个二维数组,想写一个函数来分析它的收敛情况。

我希望能找到一种简单直观的方法(现在没时间去学习一个全新的库)来绘制像下面这个草图的函数:

在这里输入图片描述

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

这样做容易吗?

1 个回答

2

你可以把你的嵌套列表转换成一个二维的numpy数组,然后用切片的方法来获取字母和周期的数量(就像在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()这一行去掉……

撰写回答