[英]How can I produce an image array as the average of multiple image arrays?
[英]How can I average an array of arrays in python?
我有一個運行多次的模擬。 每次生成一個數組並將其插入一個更大的數組中,跟蹤所有數據。 例如
record = []
for i in range(2):
r = random.random()
array = numpy.arange(20)*r
array.shape = (10,2)
record.append(array)
record = numpy.array(record)
產生:
[[[ 0. 0.88765927]
[ 1.77531855 2.66297782]
[ 3.55063709 4.43829637]
[ 5.32595564 6.21361492]
[ 7.10127419 7.98893346]
[ 8.87659274 9.76425201]
[ 10.65191128 11.53957056]
[ 12.42722983 13.3148891 ]
[ 14.20254838 15.09020765]
[ 15.97786693 16.8655262 ]]
[[ 0. 0.31394919]
[ 0.62789839 0.94184758]
[ 1.25579677 1.56974596]
[ 1.88369516 2.19764435]
[ 2.51159354 2.82554274]
[ 3.13949193 3.45344112]
[ 3.76739031 4.08133951]
[ 4.3952887 4.70923789]
[ 5.02318709 5.33713628]
[ 5.65108547 5.96503466]]]
由於每個array
代表我的程序中的模擬。 我想平均record
包含的2個不同的數組。
基本上我想要一個與數組具有相同尺寸的array
但它將是所有單獨運行的平均值。
我顯然可以循環遍歷數組但是在我的實際模擬中有很多數據,所以我認為它會非常昂貴
示例輸出(顯然它不會為零):
average = [[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]]
上面示例中的record
數組是三維的,具有形狀:
>>> record.shape
(2, 10, 2)
第一個維度對應於實驗的2次迭代。 要平均它們,你需要告訴np.average
沿axis=0
做它的事情
>>> np.average(record, axis=0)
array([[ 0. , 0.45688836],
[ 0.91377672, 1.37066507],
[ 1.82755343, 2.28444179],
[ 2.74133015, 3.19821851],
[ 3.65510686, 4.11199522],
[ 4.56888358, 5.02577194],
[ 5.4826603 , 5.93954865],
[ 6.39643701, 6.85332537],
[ 7.31021373, 7.76710209],
[ 8.22399044, 8.6808788 ]])
如果您事先知道要運行多少個模擬,那么最好完全跳過列表內容並執行以下操作:
simulations, sim_rows, sim_cols = 1000000, 10, 2
record = np.empty((simulations, sim_rows, sim_cols))
for j in xrange(simulations) :
record[j] = np.random.rand(sim_rows, sim_cols)
>>> np.average(record, axis=0)
[[ 0.50021935 0.5000554 ]
[ 0.50019659 0.50009123]
[ 0.50008591 0.49973058]
[ 0.49995812 0.49973941]
[ 0.49998854 0.49989957]
[ 0.5002542 0.50027464]
[ 0.49993122 0.49989623]
[ 0.50024623 0.49981818]
[ 0.50005848 0.50016798]
[ 0.49984452 0.49999112]]
基本上你可以使用
record.mean(axis=0)
我不確定您想要平均哪個軸,因為在您的示例中,兩個軸的尺寸為2(您的陣列具有形狀(2,10,2))。 如果你想平均最后一個,只需使用
record.mean(axis=2)
為什么你認為它會按時成本高昂? 您仍然需要執行相同數量的添加。 加法是聯想的!
做就是了:
averages = [average(subarray) for subarray in bigarray]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.