Multikey Multivalue Non Deterministic python词典

时间:2015-04-29 08:30:50

标签: python dictionary data-structures recommendation-engine fuzzy-logic

python中已经存在multi key dict,而且还有一个多值字典。我需要一个python字典,它是:

示例:

# probabilistically fetch any one of baloon, toy or car
d['red','blue','green']== "baloon" or "car" or "toy"  

d ['] == d [' green']的概率很高且d [' red']的概率!= d [& #39;红色']很低但可能

单个输出值应基于来自键的规则以概率方式确定(模糊) 例如:在上面的情况下规则可以是如果键同时具有"红色"和"蓝"然后返回" baloon" 80%的时间,如果只有蓝色然后返回"玩具" 15%的其他时间"汽车" 5%的时间。

setitem方法应该设计成可以跟随:

d["red", "blue"] =[
    ("baloon",haseither('red','green'),0.8),
    ("toy",.....)
    ,....
]

上面使用谓词函数和相应的概率为字典分配多个值。而不是上面的赋值列表,甚至字典作为赋值将是更可取的:

d["red", "blue"] ={ 
    "baloon": haseither('red','green',0.8),
    "toy": hasonly("blue",0.15),
    "car": default(0.05)
}

如果" red"在上面的气球将返回80%的时间。或绿色存在 如果蓝色存在,则返回玩具15%的时间,并且在没有任何条件的情况下返回5%的时间。

是否有任何现有的数据结构已满足python中的上述要求?如果没有那么如何修改multikeydict代码以满足python中的上述要求?

如果使用字典,那么可以有一个配置文件或使用适当的嵌套装饰器来配置上述概率谓词逻辑,而不必使用硬编码if \ else语句。

注意:上面是一个基于规则的自动响应程序应用程序的有用自动机,因此,如果python中有任何类似的基于规则的框架,即使它不使用字典结构,也要告诉我吗?

4 个答案:

答案 0 :(得分:5)

  

单个输出值应该基于来自键的规则来概率地确定(模糊),例如:在上面的情况下,规则可以是如果键具有"红色"和"蓝"然后返回" baloon" 80%的时间,如果只有蓝色然后返回"玩具" 15%的其他时间"汽车" 5%的时间。

请记住,你的案例分析并不完整,而且含糊不清,但你可以做到以下几点"在精神上" (充实期望的结果):

import random

def randomly_return(*colors):
    colors = set(*colors)
    if 'red' in colors and 'blue' in colors:
        if random.random() < 0.8:  # 80 % of the time
            return "baloon"

    if 'blue' in colors and len(colors) == 1:  # only blue in colors
        if random.random() < 0.15:
            return "toy"
        else:
            if random.random() < 0.05:
                return "car"

# other cases to consider

我会把它作为一个函数,因为它是一个函数!但是如果你坚持让它像dict一样,那么python让你通过覆盖__getitem__(IMO它不是pythonic)来做到这一点。

class RandomlyReturn(object):
    def __getitem__(self, *colors):
        return randomly_return(*colors)

>>> r = RandomlyReturn()
>>> r["red", "blue"]  # 80% of the time it'll return "baloon"
"baloon"

从您的澄清中,OP希望传递并生成:

  

randreturn((haseither(红,蓝),气球:0.8),((hasonly(蓝色),玩具:0.15)),(默认(),汽车:0.05)))

您想要生成如下函数:

funcs = {"haseither": lambda needles, haystack: any(n in haystack for n in needles),
         "hasonly": lambda needles, haystack: len(needles) == 1 and needles[1] in haystack}

def make_random_return(crits, default):
    def random_return(*colors):
        colors = set(*colors)
        for c in crits:
            if funcs[c["func"]](c["args"], colors) and random.random() > c["with_prob"]:
                return c["return_value"]
        return default
    return random_return

这里的暴击和默认值是:

crit = [{"func": "haseither", "args": ("red", "blue"), "return_value": "baloon", "with_prob": 0.8}, ...]
default = "car"  # ??
my_random_return = make_random_return(crits, default)

正如我所说,你的概率含糊不清/没有加起来,所以你很可能需要调整这个......

您可以通过在实例化时传递crit和default来扩展类定义:

class RandomlyReturn(object):
    def __init__(self, crit, default):
        self.randomly_return = make_random_return(crit, default)
    def __getitem__(self, *colors):
        return self.randomly_return(*colors)

>>> r = RandomlyReturn(crit, default)
>>> r["red", "blue"]  # 80% of the time it'll return "baloon"
"baloon"

答案 1 :(得分:4)

模拟MultiKey词典

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx不允许multi_key_dict在onces上有多个键...

(例如d["red", "green"]

可以使用__getitem__()tuple键模拟多键。如果订单无关紧要,set似乎是最好的(实际上是可投放的set,因此["red", "blue"]["blue", "red"]相同。

Simulated MultiVal Dictionary

通过使用某些数据类型,多值是固有的,可以方便地索引frozen set。标准any storage element应该提供。

非决定论

使用由规则和假设 1 定义的概率分布,使用python docs中的dict执行非确定性选择。

MultiKeyMultiValNonDeterministicDict Class

什么名字。 \ O / - 尼斯!

此类采用多个键来定义多个值的概率规则集。在项目创建期间(this recipe),所有值概率都是针对键 1 的所有组合进行预计算的。在项目访问期间(__setitem__()),选择预先计算的概率分布,并根据随机加权选择评估结果。

定义

import random
import operator
import bisect
import itertools

# or use itertools.accumulate in python 3
def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    try:
        total = next(it)
    except StopIteration:
        return
    yield total
    for element in it:
        total = func(total, element)
        yield total

class MultiKeyMultiValNonDeterministicDict(dict):

    def key_combinations(self, keys):
        """get all combinations of keys"""
        return [frozenset(subset) for L in range(0, len(keys)+1) for subset in itertools.combinations(keys, L)]

    def multi_val_rule_prob(self, rules, rule):
        """
        assign probabilities for each value, 
        spreading undefined result probabilities
        uniformly over the leftover results not defined by rule.
        """
        all_results = set([result for result_probs in rules.values() for result in result_probs])
        prob = rules[rule]
        leftover_prob = 1.0 - sum([x for x in prob.values()])
        leftover_results = len(all_results) - len(prob)
        for result in all_results:
            if result not in prob:
                # spread undefined prob uniformly over leftover results
                prob[result] = leftover_prob/leftover_results
        return prob

    def multi_key_rule_prob(self, key, val):
        """
        assign probability distributions for every combination of keys,
        using the default for combinations not defined in rule set
        """ 
        combo_probs = {}
        for combo in self.key_combinations(key):
            if combo in val:
                result_probs = self.multi_val_rule_prob(val, combo).items()
            else:
                result_probs = self.multi_val_rule_prob(val, frozenset([])).items()
            combo_probs[combo] = result_probs
        return combo_probs

    def weighted_random_choice(self, weighted_choices):
        """make choice from weighted distribution"""
        choices, weights = zip(*weighted_choices)
        cumdist = list(accumulate(weights))
        return choices[bisect.bisect(cumdist, random.random() * cumdist[-1])]

    def __setitem__(self, key, val):
        """
        set item in dictionary, 
        assigns values to keys with precomputed probability distributions
        """

        precompute_val_probs = self.multi_key_rule_prob(key, val)        
        # use to show ALL precomputed probabilities for key's rule set
        # print precompute_val_probs        

        dict.__setitem__(self, frozenset(key), precompute_val_probs)

    def __getitem__(self, key):
        """
        get item from dictionary, 
        randomly select value based on rule probability
        """
        key = frozenset([key]) if isinstance(key, str) else frozenset(key)             
        val = None
        weighted_val = None        
        if key in self.keys():
            val = dict.__getitem__(self, key)
            weighted_val = val[key]
        else:
            for k in self.keys():
                if key.issubset(k):
                    val = dict.__getitem__(self, k)
                    weighted_val = val[key]

        # used to show probabality for key
        # print weighted_val

        if weighted_val:
            prob_results = self.weighted_random_choice(weighted_val)
        else:
            prob_results = None
        return prob_results

用法

d = MultiKeyMultiValNonDeterministicDict()

d["red","blue","green"] = {
    # {rule_set} : {result: probability}
    frozenset(["red", "green"]): {"ballon": 0.8},
    frozenset(["blue"]): {"toy": 0.15},
    frozenset([]): {"car": 0.05}
}

测试

检查概率

N = 10000
red_green_test = {'car':0.0, 'toy':0.0, 'ballon':0.0}
red_blue_test = {'car':0.0, 'toy':0.0, 'ballon':0.0}
blue_test = {'car':0.0, 'toy':0.0, 'ballon':0.0}
red_blue_green_test = {'car':0.0, 'toy':0.0, 'ballon':0.0}
default_test = {'car':0.0, 'toy':0.0, 'ballon':0.0}

for _ in xrange(N):
    red_green_test[d["red","green"]] += 1.0
    red_blue_test[d["red","blue"]] += 1.0
    blue_test[d["blue"]] += 1.0
    default_test[d["green"]] += 1.0
    red_blue_green_test[d["red","blue","green"]] += 1.0

print 'red,green test      =', ' '.join('{0}: {1:05.2f}%'.format(key, 100.0*val/N) for key, val in red_green_test.items())
print 'red,blue test       =', ' '.join('{0}: {1:05.2f}%'.format(key, 100.0*val/N) for key, val in red_blue_test.items())
print 'blue test           =', ' '.join('{0}: {1:05.2f}%'.format(key, 100.0*val/N) for key, val in blue_test.items())
print 'default test        =', ' '.join('{0}: {1:05.2f}%'.format(key, 100.0*val/N) for key, val in default_test.items())
print 'red,blue,green test =', ' '.join('{0}: {1:05.2f}%'.format(key, 100.0*val/N) for key, val in red_blue_green_test.items())
red,green test      = car: 09.89% toy: 10.06% ballon: 80.05%
red,blue test       = car: 05.30% toy: 47.71% ballon: 46.99%
blue test           = car: 41.69% toy: 15.02% ballon: 43.29%
default test        = car: 05.03% toy: 47.16% ballon: 47.81%
red,blue,green test = car: 04.85% toy: 49.20% ballon: 45.95%

概率匹配规则!

脚注

  1. 分发假设

    由于规则集未完全定义,因此对概率分布进行了假设,其中大部分是在multi_val_rule_prob()中完成的。基本上任何未定义的概率将均匀地分布在剩余的值上。这是为所有键组合完成的,并为随机加权选择创建一个通用键接口。

    给出示例规则集

    d["red","blue","green"] = {
        # {rule_set} : {result: probability}
        frozenset(["red", "green"]): {"ballon": 0.8},
        frozenset(["blue"]): {"toy": 0.15},
        frozenset([]): {"car": 0.05}
    }
    

    这将创建以下分发

    'red'           = [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
    'green'         = [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
    'blue'          = [('car', 0.425), ('toy', 0.150), ('ballon', 0.425)]
    'blue,red'      = [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
    'green,red'     = [('car', 0.098), ('toy', 0.098), ('ballon', 0.800)]
    'blue,green'    = [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
    'blue,green,red'= [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
     default        = [('car', 0.050), ('toy', 0.475), ('ballon', 0.475)]
    

    如果这不正确,请告知。

答案 2 :(得分:1)

如果可以更改数据结构,则返回所需数据的函数会更简单。这将是完全灵活的,可以容纳任何类型的数据,如果您以后需要更改它们。

import random

def myfunc(*args):
    if 'red' in args:
        return 'blue'
    elif 'green' in args or 'violet' in args:
        return 'violet'
    else:
        r = random.random()
        if 0 < r < 0.2:
            return 'blue'
        else:
            return 'green'

print(myfunc('green', 'blue'))
print(myfunc('yellow'))

输出(第二行明显改变):

violet
blue

答案 3 :(得分:1)

OP希望如下,

d["red", "blue"] ={ 
    "baloon": haseither('red','green',0.8),
    "toy": hasonly("blue",0.15),
    "car": default(0.05)
}  

但这是带有嵌入逻辑的数据。为每个值定义一个函数是非常繁琐的。我建议的是分离数据和逻辑。

Python有一个数据类型,即class。可以将class的可调用实例分配给dict,让dict传递密钥并调用该对象以返回结果。

我继承并扩展multiple_key_dict以支持多键获取并将键传递给对象并调用已存储在dict中的对象。

我假设每条规则都会重新计算数据。这是Rule类,它有规则列表。规则是Python表达式,它可以访问len函数和keys列表。所以可以编写像len(keys) == 1 and 'blue' in keys这样的规则。

class Rule(object):

    def __init__(self, rule, data):
        self.rule = rule
        self.data = data

这是Data类,它有两组数据和规则。

class Data(object):
    def __init__(self, rules):
        self.rules= rules

    def make_choice(self, data):
        data = tuple(self.make_list_of_values(data))
        return random.choice(data)

    def make_list_of_values(self, data):
        for val, weight in data:
            percent = int(weight * 100)
            for v in [val] * percent:
                yield v

    def __call__(self, keys):
        for rule in self.rules:
            if eval(rule.rule,dict(keys=keys)):
                return self.make_choice(rule.data)

这是RuleDict,但无法获取非callables。

class RuleDict(multi_key_dict):
    def __init__(self, *args, **kwargs):
        multi_key_dict.__init__(self, *args, **kwargs)

    def __getitem__(self, keys):
        if isinstance(keys, str):
            keys = (keys, )
        keys_set = frozenset(keys)
        for key in self.keys():
            key = frozenset(key)
            if keys_set <= key:
                return multi_key_dict.__getitem__(self,keys[0])(keys)
        raise KeyError(keys)

用法示例,

d = RuleDict()
rule1 = Rule('"red" in keys and "green" in keys',(('baloon',0.8), ('car',0.05), ('toy',0.15)))
rule2 = Rule('len(keys) ==1 and "blue" in keys',(('baloon',0.25), ('car',0.35), ('toy',0.15)))
data = Data((rule1, rule2))
d['red','blue','green'] = data

print(d['red','green'])  

d['red','green']使用已分配的键调用对象并返回结果。

另一种方法是使dict可调用。这个似乎是一种合理的方法,因为数据和逻辑是分开的。通过这个,您将键和逻辑(可调用的)传递给dict并返回结果。 f.e.,

def f(keys, data):
    pass # do the logic and return data

d['red','blue','green'] = ('baloon', 'car', 'toy')

现在拨打dict

d(('red','blue'),f)

这是可调用的dict。如果没有给出可调用,则只返回整个数据。

class callable_mkd(multi_key_dict):
    def __init__(self, *args, **kwargs):
        multi_key_dict.__init__(self, *args, **kwargs)

    def __call__(self, keys, process=None):
        keys_set = frozenset(keys)
        for key in self.keys():
            key = frozenset(key)
            if keys_set <= key:
                if process:
                    return process(keys, self[keys[0]])
                return self[keys[0]]
        raise KeyError(keys)