[英]Reshaping numpy array from list
我對ndarray的形狀存在以下問題:
out.shape = (20,)
reference.shape = (20,0)
norm = [out[i] / np.sum(out[i]) for i in range(len(out))]
# norm is a list now so I convert it to ndarray:
norm_array = np.array((norm))
norm_array.shape = (20,30)
# error: operands could not be broadcast together with shapes (20,30) (20,)
diff = np.fabs(norm_array - reference)
如何將norm_array的形狀從(20,30)更改為(20,)或引用(20,30),以便減去它們?
編輯:有人可以解釋我,為什么它們具有不同的形狀,如果我可以使用norm_array [0] [0]和reference [0] [0]訪問兩個單個元素?
我不確定您到底想做什么,但是這里有一些有關numpy數組的信息。
一維numpy數組是形狀為單值元組的行向量:
>>> np.array([1,2,3]).shape
(3,)
您可以通過傳遞嵌套列表來創建多維數組。 每個子列表是長度為1的一維行向量,其中有3個。
>>> np.array([[1],[2],[3]]).shape
(3,1)
這是奇怪的部分。 您可以創建相同的數組,但將列表留空。 您最終得到3個長度為0的行向量。
>>> np.array([[],[],[]]).shape
(3,0)
這就是您要reference
數組,它是具有結構但沒有值的數組。 這使我回到原來的觀點:
您不能減去一個空數組。
如果我用您描述的形狀制作2個數組,則會出現錯誤
In [1856]: norm_array=np.ones((20,30))
In [1857]: reference=np.ones((20,0))
In [1858]: norm_array-reference
...
ValueError: operands could not be broadcast together with shapes (20,30) (20,0)
但這與您的不同。 但是,如果我更改reference
的形狀,則錯誤消息會匹配。
In [1859]: reference=np.ones((20,))
In [1860]: norm_array-reference
...
ValueError: operands could not be broadcast together with shapes (20,30) (20,)
因此,您的(20,0)
是錯誤的。 我不知道您是否輸錯了什么。
但是,如果我在最后一個維度中用2 reference
2d,則廣播工作正常,產生的差異與形狀匹配(20,30):
In [1861]: reference=np.ones((20,1))
In [1862]: norm_array-reference
如果reference = np.zeros((20,))
,那么我可以使用reference[:,None]
添加該單例最后一個維度。
如果reference
為(20,),則不能執行reference[0][0]
。 reference[0][0]
僅適用於最后一個暗角中至少具有1的2d數組。 reference[0,0]
是索引2d數組單個元素的首選方法。
到目前為止,這是正常的陣列尺寸和廣播。 使用中會學到的東西。
===============
我對out
的形狀感到困惑。 如果為(20,), norm_array
結果如何為(20,30)。 out
必須包含20個數組或列表,每個數組或列表包含30個元素。
如果out
是2d數組,我們可以進行標准化而無需迭代
In [1869]: out=np.arange(12).reshape(3,4)
與列表理解:
In [1872]: [out[i]/np.sum(out[i]) for i in range(out.shape[0])]
Out[1872]:
[array([ 0. , 0.16666667, 0.33333333, 0.5 ]),
array([ 0.18181818, 0.22727273, 0.27272727, 0.31818182]),
array([ 0.21052632, 0.23684211, 0.26315789, 0.28947368])]
In [1873]: np.array(_) # and to array
Out[1873]:
array([[ 0. , 0.16666667, 0.33333333, 0.5 ],
[ 0.18181818, 0.22727273, 0.27272727, 0.31818182],
[ 0.21052632, 0.23684211, 0.26315789, 0.28947368]])
取行總和,並告訴它保留2d以方便進一步使用
In [1876]: out.sum(axis=1,keepdims=True)
Out[1876]:
array([[ 6],
[22],
[38]])
現在分裂
In [1877]: out/out.sum(axis=1,keepdims=True)
Out[1877]:
array([[ 0. , 0.16666667, 0.33333333, 0.5 ],
[ 0.18181818, 0.22727273, 0.27272727, 0.31818182],
[ 0.21052632, 0.23684211, 0.26315789, 0.28947368]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.