2016-08-13 44 views
1

這是我的代碼,我想要做的是將我寫入的函數應用於明暗數列。要知道項目的進展,我希望做類似的事情,我可以與如果i % 100 == 0: print i如何計算函數被調用的次數?

from sklearn.mixture import GMM 

gmm = GMM(n_components=2) 

def getFunc(x): 
    print 1 
    return gmm.fit_predict(np.expand_dims(x,axis=1)) 

newX = np.apply_along_axis(getFunc, 0, inputX) 

回答

1

有沒有這樣的設施for循環做的 - 事實上,不可能有,因爲apply_along_axis是單片調用(出於性能原因,這是一件好事),主要發生在C/CPython中。沒有任何工具可以將已處理過的項目數量回傳給python--事實上,在考慮Global Interpreter Lock時,我甚至都沒有看到這種情況甚至會發生。考慮到它實際上非常接近拉姆達(你可能會得到一個速度),因此,除非你的getFunc更新了global計數器 - 這可能或可能不是一個好主意,所以不行,這是行不通的。如果您使用lambda x: gmm.fit_predict(np.expand_dims(x, axis=1))而不是getFunc,或者僅使用np.vectorize,則可以改進!)。

+1

調用lambda並不比調用使用'def'創建的等價函數快。 –

+0

@ PM2Ring是不是有這樣的功能導致本地人導致不得不垃圾收集/解構?另外,請注意我試圖避免的「打印1」(IO相對較慢)。 –

+0

當然,打印肯定會減慢執行速度。我只發佈了我以前的評論,因爲最後一段(某種)暗示使用lambda會比常規的'def'函數更快,並且情況並非如此,假設lambda和常規函數包含相同的代碼。 –

2

你可以嘗試爲你的函數寫一個裝飾器。

from functools import wraps 
from sklearn.mixture import GMM 

gmm = GMM(n_components=2) 

def log_every(n): 
    def decorator(fn) 
     counter = 0 
     @wraps(fn) 
     def wrapper(*args, **kwargs): 
      counter += 1 
      if counter % n == 0: 
       print(n) 
      return fn(*args, **kwargs) 
     return wrapper 
    return decorator 

@log_every(100) 
def getFunc(x): 
    return gmm.fit_predict(np.expand_dims(x,axis=1)) 

newX = np.apply_along_axis(getFunc, 0, inputX) 

但是,正如@MarcusMüller指出的那樣,性能可能會受損。

1

一個global計數器應該工作,所以將一個可變的反

Out[1471]: array([12, 15, 18, 21]) 
In [1472]: A=np.arange(12).reshape(3,4) 
In [1473]: def foo(x): 
     ...:  counter[0] +=1 
     ...:  print(counter) 
     ...:  return sum(x) 
     ...: 
In [1474]: counter=[0] 
In [1475]: np.apply_along_axis(foo,0,A) 
[1] 
[2] 
[3] 
[4] 
Out[1475]: array([12, 15, 18, 21]) 

In [1476]: [sum(col) for col in A.T] 
Out[1476]: [12, 15, 18, 21] 
In [1477]: A.sum(axis=0) 
Out[1477]: array([12, 15, 18, 21]) 

你爲什麼要使用apply_along_axis,在這種情況下apply_along_axis是什麼? inputX的尺寸是多少?

在2D情況下,apply_along_axis基本上是:

[sum(A[(slice(None),i)]) for i in range(A.shape[1])] 

如果A更高尺寸的,它需要在(slice(None),i,j...)遍歷所有i,j...照顧。但是還有其他方式來產生這些指數。它提供了便利,而不是速度或功能。