3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用類裝飾器來生成度量標(biāo)準(zhǔn)方法的列表。這樣做的好處是,您可以在類定義時(shí)生成度量標(biāo)準(zhǔn)方法的列表,而不是每次
printResults
調(diào)用時(shí)都重新生成該列表。另一個(gè)優(yōu)點(diǎn)是您不必手動(dòng)維護(hù)
ClassificationResults.metrics
列表。您無需在兩個(gè)位置上拼寫方法的名稱,因此它是DRY-er,而且,如果您添加了另一個(gè)指標(biāo),則不必記住也要更新ClassificationResults.metrics
。您只需要給它一個(gè)以開頭的名稱即可metrics_
。由于每種度量方法都返回一個(gè)相似的對(duì)象,因此您可以考慮將該概念形式化為類(例如
Metric
,下面的)。這樣做的一個(gè)好處是您可以定義一種__repr__
方法來處理結(jié)果的打印方式。注意printResults
(下面)變得多么簡單。
def register_metrics(cls):
for methodname in dir(cls):
if methodname.startswith('metric_'):
method = getattr(cls, methodname)
cls.metrics.append(method)
return cls
class Metric(object):
def __init__(self, pos, total):
self.pos = pos
self.total = total
def __repr__(self):
msg = "{p} instances labelled positive. {t} of them correct (recall={d:.2g})"
dec = self.pos / float(self.total)
return msg.format(p=self.total, t=self.pos, d=dec)
@register_metrics
class ClassificationResults(object):
metrics = []
def metric_recall(self):
tpos, pos = 1, 2
return Metric(tpos, pos)
def metric_precision(self):
tpos, true = 3, 4
return Metric(tpos, true)
def printResults(self):
for method in self.metrics:
print(method(self))
foo = ClassificationResults()
foo.printResults()
添加回答
舉報(bào)