所以我想實現一個矩陣標準化方法。 要做到這一點,我已經告訴numpy - 沿指定軸操作
減去平均值除以每個維度
,並驗證標準偏差:
此處理後,每維度具有零均值和單位差異。
這聽起來很簡單...
import numpy as np
def standardize(X : np.ndarray,inplace=True,verbose=False,check=False):
ret = X
if not inplace:
ret = X.copy()
ndim = np.ndim(X)
for d in range(ndim):
m = np.mean(ret,axis=d)
s = np.std(ret,axis=d)
if verbose:
print(f"m{d} =",m)
print(f"s{d} =",s)
# TODO: handle zero s
# TODO: subtract m along the correct axis
# TODO: divide by s along the correct axis
if check:
means = [np.mean(X,axis=d) for d in range(ndim)]
stds = [np.std(X,axis=d) for d in range(ndim)]
if verbose:
print("means=\n",means)
print("stds=\n",stds)
assert all(all(m < 1e-15 for m in mm) for mm in means)
assert all(all(s == 1.0 for s in ss) for ss in stds)
return ret
例如對於ndim == 2
,我們可以得到類似於
A=
[[ 0.40923704 0.91397416 0.62257397]
[ 0.15614258 0.56720836 0.80624135]]
m0 = [ 0.28268981 0.74059126 0.71440766] # can broadcast with ret -= m0
s0 = [ 0.12654723 0.1733829 0.09183369] # can broadcast with ret /= s0
m1 = [ 0.33333333 -0.33333333] # ???
s1 = [ 0.94280904 0.94280904] # ???
我該怎麼做?
通過Broadcast an operation along specific axis in python來看,我想我可能會尋找一種方式來創建
m[None, None, None, .., None, : , None, None, .., None]
凡在指數d
只有一個:
。
但即使我知道如何做到這一點,我不知道它會工作。
把那'np.append'下來用心了,往回走。這很危險。 http://stackoverflow.com/questions/42563335/how-to-append-a-selection-of-a-numpy-array-to-an-empty-numpy-array – hpaulj
@hpaulj沒有工作,無論如何。 =)也試圖「破解」2D案例,發現「::」的索引不符合我的期望。 – User1291
使用'keepdims',從而避免所有那些明確的暗淡擴展工作? – Divakar