2

我有一组数组。我还有一个单独的数组 (T) 来比较集合中的每个数组。我尝试使用 SequenceMatcher 来执行此操作,但不知道如何循环它,以便将集合中的每个数组与 T 进行比较。

这是针对遗传算法的适应度函数。我是 python 新手,已经尝试了几件事。下面的代码可能是可笑的!

import difflib

parents = set()
while len(parents) < 5:
    a = tuple(np.random.choice([0, 1], size=(10)))
    if a not in parents: parents.add(a) # To make them different
parents = np.array([list(x) for x in parents])

print(pop_sp())

T = tuple(np.random.choice([0, 1], size=(20)))

for i in parents:
    fitness=difflib.SequenceMatcher(None,i,T)
    print(fitness.ratio)

我希望输出是

[[0 0 1 0 0 0 0 1 1 0]  
 [0 0 0 1 1 0 1 0 0 0]  
 [1 0 1 1 1 1 0 0 1 1]  
 [0 0 1 0 0 1 1 0 0 0]  
 [1 1 0 1 1 0 0 1 0 0]] 

以及每个数组与 T 的相似性百分比。
但我得到以下信息:

[[0 0 1 0 0 0 0 1 1 0]  
 [0 0 0 1 1 0 1 0 0 0]  
 [1 0 1 1 1 1 0 0 1 1]  
 [0 0 1 0 0 1 1 0 0 0]  
 [1 1 0 1 1 0 0 1 0 0]] 
<bound method SequenceMatcher.ratio of <difflib.SequenceMatcher object at 0x1c1ea8ec88>>  
<bound method SequenceMatcher.ratio of <difflib.SequenceMatcher object at 0x1c1dff9438>>  
<bound method SequenceMatcher.ratio of <difflib.SequenceMatcher object at 0x1c1ea8ec88>>  
<bound method SequenceMatcher.ratio of <difflib.SequenceMatcher object at 0x1c1dff9438>>  
<bound method SequenceMatcher.ratio of <difflib.SequenceMatcher object at 0x1c1ea8ec88>>
4

1 回答 1

1

你必须调用适应度函数

for i in parents:
    fitness=difflib.SequenceMatcher(None,i,T)
    ratios = fitness.ratio()
    print(ratios)
于 2019-08-17T17:18:41.947 回答