一開始寫了個簡單版本log_norm0
愕乎,只能逐元素一個一個得進行阵苇。不用想,對元素個數(shù)多的向量感论,肯定慢成烏龜绅项。
后來想到使用一個指示函數(shù),來區(qū)分分段的兩種情況比肄,就得到log_norm1
快耿。不過這種情況比較特殊,不是每次都能成功構(gòu)造的芳绩。
最后掀亥,查到numpy
中有函數(shù)piecewise(x, condlist, funclist, *args, **kw)
,它是專門用來構(gòu)造分段函數(shù)妥色,x
是輸入搪花,condlist
表示分段的條件,funclist
就表示對應(yīng)分段的處理函數(shù)嘹害。這就得到了log_norm2
撮竿。
# elementwise
def log_norm0(x):
if x >= 0:
return np.log(x + 1)
else:
return - np.log(- x + 1)
# indicator
def log_norm1(x):
# ind = np.where(x > 0, 1, 0)
ind = (x > 0)
return np.log(x * ind + 1) - np.log(- x * (1.0 - ind) + 1)
# numpy.piecewise()
def log_norm2(x):
return np.piecewise(x, [x >= 0, x < 0], [lambda x: np.log(1 + x), lambda x: - np.log(1 - x)])
最后,觀察一個各個函數(shù)的運行時間笔呀。
tic = time.time()
for i in range(x.size):
y[i] = log_norm0(x[i])
toc = time.time()
print('log0: ', toc - tic)
tic = time.time()
y = log_norm1(x)
toc = time.time()
print('log1: ', toc - tic)
tic = time.time()
z = log_norm2(x)
toc = time.time()
print('log2: ', toc - tic)
觀察結(jié)果幢踏,還是使用指示函數(shù)的方法最快,不過跟piecewise差別不大许师。
log0: 33.59282732009888
log1: 0.4863457679748535
log2: 0.5942573547363281
參考資料:
- https://blog.csdn.net/shu15121856/article/details/76080060
- https://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html
擴展資料(待填坑):
https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.call.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.frompyfunc.html
https://blog.csdn.net/kezunhai/article/details/46127845