我需要计算使用Python在串行端口上传输的传感器数据的移动平均值。我可以找到关于numpy的所有样本在程序启动之前使用文件中的数据或数组中的硬编码数据。
在我的情况下,程序启动时我没有任何数据。数据每秒都会实时显示。我想在数据到达串口时平滑数据。
我在Arduino上工作但在Python中也需要它。有人可以指示我实时(单个值随时间变化)样本而不是批量样本。
答案 0 :(得分:2)
以下是如何将一个读数一次添加到正在运行的读数集中并返回平均值。我预先填充了读数列表以显示其实际效果,但在您的程序中,您只需从一个空列表开始:readings = []
我假设您希望在平均值中包含最后的x个读数,而不是包括所有读数。这就是max_samples
参数的用途。
没有numpy:
readings = [1, 2, 3, 4, 5, 6, 7, 8, 9]
reading = 10
max_samples = 10
def mean(nums):
return float(sum(nums)) / max(len(nums), 1)
readings.append(reading)
avg = mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings.pop(0)
print 'readings saved for next time:', readings
结果:
current average = 5.5
readings used for average: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
readings saved for next time: [2, 3, 4, 5, 6, 7, 8, 9, 10]
与numpy:
import numpy as np
readings = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
reading = 10
max_samples = 10
readings = np.append(readings, reading)
avg = np.mean(readings)
print 'current average =', avg
print 'readings used for average:', readings
if len(readings) == max_samples:
readings = np.delete(readings, 0)
print 'readings saved for next time:', readings
结果:
current average = 5.5
readings used for average: [ 1 2 3 4 5 6 7 8 9 10]
readings saved for next time: [ 2 3 4 5 6 7 8 9 10]
答案 1 :(得分:1)
作为课程实施:
class StreamingMovingAverage:
def __init__(self, window_size):
self.window_size = window_size
self.values = []
self.sum = 0
def process(self, value):
self.values.append(value)
self.sum += value
if len(self.values) > self.window_size:
self.sum -= self.values.pop(0)
return float(self.sum) / len(self.values)