統計アキュムレータを使用すると、増分計算を実行できます。たとえば、任意の時間に与えられた数値のストリームの算術平均を計算するために、与えられたアイテムの現在の数n
とそれらの合計を追跡するオブジェクトを作成できますsum
。平均を要求すると、オブジェクトは単純に を返しますsum/n
。
このようなアキュムレータを使用すると、新しい数値が与えられたときに、合計とカウント全体を再計算する必要がないという意味で、インクリメンタルに計算できます。
同様のアキュムレータを他の統計用に作成できます ( C++ 実装用のブースト ライブラリを参照)。
Python でアキュムレータをどのように実装しますか? 私が思いついたコードは次のとおりです。
class Accumulator(object):
"""
Used to accumulate the arithmetic mean of a stream of
numbers. This implementation does not allow to remove items
already accumulated, but it could easily be modified to do
so. also, other statistics could be accumulated.
"""
def __init__(self):
# upon initialization, the numnber of items currently
# accumulated (_n) and the total sum of the items acumulated
# (_sum) are set to zero because nothing has been accumulated
# yet.
self._n = 0
self._sum = 0.0
def add(self, item):
# the 'add' is used to add an item to this accumulator
try:
# try to convert the item to a float. If you are
# successful, add the float to the current sum and
# increase the number of accumulated items
self._sum += float(item)
self._n += 1
except ValueError:
# if you fail to convert the item to a float, simply
# ignore the exception (pass on it and do nothing)
pass
@property
def mean(self):
# the property 'mean' returns the current mean accumulated in
# the object
if self._n > 0:
# if you have more than zero items accumulated, then return
# their artithmetic average
return self._sum / self._n
else:
# if you have no items accumulated, return None (you could
# also raise an exception)
return None
# using the object:
# Create an instance of the object "Accumulator"
my_accumulator = Accumulator()
print my_accumulator.mean
# prints None because there are no items accumulated
# add one (a number)
my_accumulator.add(1)
print my_accumulator.mean
# prints 1.0
# add two (a string - it will be converted to a float)
my_accumulator.add('2')
print my_accumulator.mean
# prints 1.5
# add a 'NA' (will be ignored because it cannot be converted to float)
my_accumulator.add('NA')
print my_accumulator.mean
# prints 1.5 (notice that it ignored the 'NA')
興味深い設計上の問題が発生します。
- アキュムレータをスレッドセーフにする方法は?
- アイテムを安全に削除するには?
- 他の統計を簡単にプラグインできるように設計する方法 (統計のファクトリ)