绘制数组中的每个第 n 个元素

Haz*_*ldo 2 python numpy matplotlib

我正在从头开始编写一个简单的神经网络。神经网络是用一种方法实现的simple_1_layer_classification_NN。对于每个 Epoch(神经网络的训练运行),正如您从for loop(在下面的代码中)看到的那样,我将成本(误差范围)值附加到数组中costs。问题是训练次数可能多达数千甚至数百万。这意味着costs数组可以附加很多cost元素。

因为我不想在图表上绘制数千或数百万个数据点,所以我想做的是,无论数组中有多少元素costs,我只想从中绘制 100 个数据点,展开尽可能平等。例如,如果有 10 个元素,则绘制所有 10 个元素。如果有 100 个元素,则绘制所有 100 个元素。任何高于 100 的值,仅绘制等间隔的 100 个数据点。例如,每隔一个数据点绘制 200 个图。如果为 500,则每隔 5 个元素绘制一次。即使有 102 个元素,也只绘制 100 个数据点,并尽可能间隔开。我希望这是有道理的。这可以吗?请注意,我只包含与问题最相关的部分代码。如果有带点的注释,# ......我只是表明这里有代码,但我没有包含它,因为它与问题无关。

非常感谢您的帮助。


 def simple_1_layer_classification_NN(self, dataset_input_matrix, output_data_labels, input_dimension, epochs, activation_func='sigmoid', learning_rate=0.2, cost_func='squared_error'):
        # ...............
        cost = float()
        costs = []
        # ................

        # We perform the training based on the number of epochs specified
        for i in range(epochs):

                 #....................
                 # Cost: the cost function to calculate the prediction error margin
                 cost = chosen_cost_func(pred, output_data_labels[ri])

                costs.append(cost)
        #.....................

    plt.plot(costs)
    plt.show()
Run Code Online (Sandbox Code Playgroud)

Sev*_*eux 6

关于什么

x = xdata[::10]
x = ydata[::10]
plt.plot(x, y)
plt.show()
Run Code Online (Sandbox Code Playgroud)

它将绘制 xdata、ydata 中的每 10 个点

在你的情况下

x = None
y = None
l = len(xdata) 
if l < 100:
    x = xdata[::]
    y = ydata[::]
elif l < 200:
    x = xdata[::2]
    y = ydata[::2]
elif l < 500:
    x = xdata[::5]
    y = ydata[::5]
Run Code Online (Sandbox Code Playgroud)

更新

不确定它是否相关,但您也可以尝试使用自定义步幅。它将指向相同的数据缓冲区,但使用不同的元数据来逐步跨过数据。

要查看的函数是https://docs.scipy.org/doc/numpy/reference/ generated/numpy.lib.stride_tricks.as_strided.html#numpy.lib.stride_tricks.as_strided ,它位于 stride_tricks 中是有原因的- 你会有一些时间来适应它。将 writeable 设置为 False,这样就不会弄乱原始数据。简单的例子在这里