为什么在运行此for循环时笔记本会崩溃,并且解决了什么问题?

问题描述 投票:0回答:1

我已获取有关卡尔曼滤波器的代码,并正在尝试遍历数据的每一列。我想发生的是:

  1. 列数据被送入过滤器
  2. 已过滤的列数据(xhat)被放置到另一个DataFrame中(已过滤)
  3. 已过滤的列数据(xhat)用于产生视觉效果。

我创建了一个for循环来遍历列数据,但是当我运行单元格时,我使笔记本电脑崩溃了。当它没有崩溃时,我会收到以下警告:

C:\Users\perso\Anaconda3\envs\learn-env\lib\site-packages\ipykernel_launcher.py:45: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).

谢谢您的帮助。我希望这个问题足够详细。我炸了最后一个。

    '''A Python implementation of the example given in pages 11-15 of "An
Introduction to the Kalman Filter" by Greg Welch and Gary Bishop,
University of North Carolina at Chapel Hill, Department of Computer
Science, TR 95-041,
https://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf'''

# by Andrew D. Straw
import numpy as np
import matplotlib.pyplot as plt
# dataframe created to hold filtered data
filtered = pd.DataFrame()

# intial parameters
for column in data:
    n_iter = len(data.index) #number of iterations equal to sample numbers
    sz = (n_iter,) # size of array
    z =  data[column] # observations
    Q = 1e-5 # process variance

# allocate space for arrays
    xhat=np.zeros(sz)      # a posteri estimate of x
    P=np.zeros(sz)         # a posteri error estimate
    xhatminus=np.zeros(sz) # a priori estimate of x
    Pminus=np.zeros(sz)    # a priori error estimate
    K=np.zeros(sz)         # gain or blending factor
    R = 1.0**2 # estimate of measurement variance, change to see effect

    # intial guesses
    xhat[0] = z[0]
    P[0] = 1.0

    for k in range(1,n_iter):
        # time update
        xhatminus[k] = xhat[k-1]
        Pminus[k] = P[k-1]+Q

        # measurement update
        K[k] = Pminus[k]/( Pminus[k]+R )
        xhat[k] = xhatminus[k]+K[k]*(z[k]-xhatminus[k])
        P[k] = (1-K[k])*Pminus[k]
        # add new data to created dataframe
        filtered.assign(a = [xhat])
        #create visualization of noise reduction
        plt.rcParams['figure.figsize'] = (10, 8)
        plt.figure()
        plt.plot(z,'k+',label='noisy measurements')
        plt.plot(xhat,'b-',label='a posteri estimate')
        plt.legend()
        plt.title('Estimate vs. iteration step', fontweight='bold')
        plt.xlabel('column data')
        plt.ylabel('Measurement')
python-3.x numpy for-loop matplotlib jupyter-notebook
1个回答
0
投票

这似乎是一个非常简单的错误。该警告表示在创建警告之前,您试图绘制的图形超出了当前限制(可以更改该参数,但默认情况下将其设置为20)。这是因为在for循环的每次迭代中,您都会创建一个新图形。根据n_iter的大小,您可能会打开数百或数千个图形。这些图每个都需要资源来生成和显示,因此您在系统上创建了非常大的资源负载。它正在处理非常缓慢或完全崩溃。无论如何,解决方案是绘制更少的数字。

我不知道您要在循环中绘制什么,但是看起来循环的每次迭代都对应一个时间步长,并且您希望在每个时间步长绘制估计值和实际值。在这种情况下,您需要在循环之外而不是在每次迭代时定义一次图形和图形选项。但是,执行此操作的更好方法可能是提前生成要绘制的所有数据,并将其存储在易于绘制的数据类型(如列表)中,然后在末尾绘制一次。

© www.soinside.com 2019 - 2024. All rights reserved.