在減法過程中,您需要f
到broadcast跨越M
。要做到這一點,形狀必須兼容。 f
必須reshaped
f.reshape(-1) - M
f = np.random.random_integers(0,1,(15,1))
M = np.random.random_integers(0,1,(5,15))
>>> f.shape
(15, 1)
>>> M.shape
(5, 15)
>>> g = f.reshape(-1)
>>> g.shape
(15,)
>>> g
array([1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0])
>>> g - M
array([[ 0, 1, 0, 0, -1, 1, 0, -1, -1, 0, 0, -1, 1, 0, 0],
[ 0, 1, 1, 0, -1, 1, 0, 0, -1, 1, 0, 0, 0, 0, -1],
[ 0, 1, 0, -1, -1, 1, 0, 0, 0, 0, 0, -1, 0, 0, -1],
[ 1, 0, 0, -1, 0, 0, 1, -1, -1, 1, 0, -1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0]])
>>>
.ravel()
也適用。
>>> f.ravel()
array([1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0])
>>> f.ravel() - M
array([[ 0, 1, 0, 0, -1, 1, 0, -1, -1, 0, 0, -1, 1, 0, 0],
[ 0, 1, 1, 0, -1, 1, 0, 0, -1, 1, 0, 0, 0, 0, -1],
[ 0, 1, 0, -1, -1, 1, 0, 0, 0, 0, 0, -1, 0, 0, -1],
[ 1, 0, 0, -1, 0, 0, 1, -1, -1, 1, 0, -1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0]])
>>>
最後:
>>> np.sum(np.absolute(f.reshape(-1) - M))
30
>>>
嘗試'(np.sum(abs(f.shapepe(f.shape [0]) - M)))'' – wwii