2012-12-13 32 views
2

我有2個函數可以給出精度和召回分數,我需要在使用這兩個分數的同一個庫中定義一個諧波平均函數。功能如下:python函數中的諧波含義?

這裏的功能是:

def precision(ref, hyp): 
    """Calculates precision. 
    Args: 
    - ref: a list of 0's and 1's extracted from a reference file 
    - hyp: a list of 0's and 1's extracted from a hypothesis file 
    Returns: 
    - A floating point number indicating the precision of the hypothesis 
    """ 
    (n, np, ntp) = (len(ref), 0.0, 0.0) 
    for i in range(n): 
      if bool(hyp[i]): 
        np += 1 
        if bool(ref[i]): 
          ntp += 1 
    return ntp/np 

def recall(ref, hyp): 
    """Calculates recall. 
    Args: 
    - ref: a list of 0's and 1's extracted from a reference file 
    - hyp: a list of 0's and 1's extracted from a hypothesis file 
    Returns: 
    - A floating point number indicating the recall rate of the hypothesis 
    """ 
    (n, nt, ntp) = (len(ref), 0.0, 0.0) 
    for i in range(n): 
      if bool(ref[i]): 
        nt += 1 
        if bool(hyp[i]): 
          ntp += 1 
    return ntp/nt 

將調和平均數功能是什麼樣的? 我只有這一點,但我知道它不是正確的:

def hmean(*args): 
    return len(args)/sum(1./val for val in args) 

要計算的precisionrecall,利用調和平均數:

def F1(precision, recall): 
    (2*precision*recall)/(precision+recall) 
+0

你能解釋一下爲什麼你認爲它不對嗎?當我嘗試運行程序時,我可能會幫助.. –

+0

我得到了TypeError:無法乘以類型'list'的非int的序列 – marth17

+0

您能告訴我們您如何使用F1功能嗎?看起來像你傳遞的參數是不正確的。特別是'F1'的兩個參數必須是數字。 –

回答

0

與您F1功能的輕微變化,並與你定義的相同precisionrecall功能,我有這樣的工作:

def F1(precision, recall): 
    return (2*precision*recall)/(precision+recall) 

r = [0,1,0,0,0,1,1,0,1] 
h = [0,1,1,1,0,0,1,0,1] 
p = precision(r, h) 
rec = recall(r, h) 
f = F1(p, rec) 
print f 

審查特別是使用變量我有。您必須計算每個函數的結果並將它們傳遞給函數F1

+0

嗯我得到TypeError:F1()需要剛好1位置參數(2給出) – marth17

+0

啊,nvm得到它的工作。謝謝!! – marth17

2

下面將與任意數量的參數工作

result = hmean(precision, recall) 

有兩個問題與你的函數:

  1. 無法返回值。
  2. 在某些版本的Python上,它將整數除法用於整數參數,截斷結果。
+0

抱歉,參數是什麼?我正在使用花車是嗎? – marth17

+0

@ marth17:任何數字類型都可以使用。 – NPE

+0

前2個函數返回值,我如何將這些函數合併到我的hmean函數中?我猜這就是我想問什麼要爲'參數' – marth17