gpt4 book ai didi

python - 基于多个数据点的评分

转载 作者:行者123 更新时间:2023-12-01 01:01:07 25 4
gpt4 key购买 nike

需要有关最简单方法的指导。我有多个 Assets ,每个 Assets 都有多个数据点。我希望根据每个数据点的决策为每个 Assets 分配一个值。举个例子,每个 Assets 是一栋房子,数据点包括 window 数量、车库门、破损的栅栏等,每个房子都会有一个分数。

除了数百个 if 语句和从分数中添加/减去之外,是否有推荐的编码方式?

我计划如何执行此操作的示例

def score_house(house):
# score house
score = 0
if (house.windows > 2): score += 10
if (house.garage): score += 10
if (house.fence == 'broken'): score += 80
return score

最佳答案

我认为您也可以在这里使用“责任链”模式:

The pattern allows multiple objects to handle the request without coupling sender class to the concrete classes of the receivers. The chain can be composed dynamically at runtime with any handler that follows a standard handler interface.

使用此模式的好处在于,您可以在单独的模块中定义和扩展不同的评分器,并在运行时根据问题条件动态组合它们。以下是您可以如何做到这一点。首先,定义一个父记分器类:

from functools import reduce


class BaseScorer(object):

def __init__(self):
self._next_scorer = None

def set_next(self, scorer):
self._next_scorer = scorer

return scorer

def _call_next(self, house, score):

if self._next_scorer is None:
return score

return self._next_scorer.score(house, score)

def score(self, house, score=0):
raise NotImplementedError

@staticmethod
def chain(scorers):
reduce(lambda x, y: x.set_next(y), scorers)

return scorers[0]

然后,定义各种记分器类,例如:

class WindowScorer(BaseScorer):

def score(self, house, score=0):

if house.windows > 2:
score = score + 10

return self._call_next(house, score)


class GarageScorer(BaseScorer):

def score(self, house, score=0):

if house.garage:
score = score + 10

return self._call_next(house, score)


class FenceScorer(BaseScorer):

def score(self, house, score=0):

if house.fence == 'broken':
score = score - 5

return self._call_next(house, score)

这就是它的使用方式:

scorer = BaseScorer.chain([
WindowScorer(),
GarageScorer(),
FenceScorer()
])

house = House(windows=4, garage=True, fence='nice')
score = scorer.score(house)

关于python - 基于多个数据点的评分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55788577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com