gpt4 book ai didi

python - 在 matplotlib 中绘制二维函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:49 37 4
gpt4 key购买 nike

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

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

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

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

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

我正在寻找可以轻松直观地(现在没有时间花 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

这很容易做到吗?

最佳答案

您可以将嵌套列表转换为 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() 行...

关于python - 在 matplotlib 中绘制二维函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22354320/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com