在matplotlib中绘制2D函数

时间:2014-03-12 14:15:39

标签: python matplotlib neural-network

亲爱的编码员和科学家们:)

我正在使用带有numpy和matplotlib的python来模拟感知器,我很自豪地说它的效果非常好。

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

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

所以我得到了这个2D数组,并希望编写一个能够让我分析收敛的函数。

我正在寻找一些容易和直观的东西(现在没有时间研究一个全新的图书馆5个小时)绘制一个像这个草图的功能:

enter image description here

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 个答案:

答案 0 :(得分:2)

您可以将嵌套列表转换为2d numpy数组,然后使用切片来获取alpha和epoch计数(就像在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()行,如果你真的不希望情节看起来像草图......