[英]Controlling Mutation in 39bit string as a candidate solution in genetic algorithm
我正在研究優化問題。 我有X
個救護車位置,其中X
的范圍是1-39
。
有43
個號碼[救護車位置]可供選擇(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39)
,我們選擇其中的3
,因為我有 3 個救護車。
我只能將我的救護車停在 1-39 個位置中的三個位置(限制)。 假設我想把我的 Ambulance 放在5th, 19th, and 31 positions.
-- Chromosome 1= [000010000000000000100000000000100000000]
。 在上面的演示中, I am turning on 5-bit, 19-bit, and 31-bit.
是否可以稍微接近原始解決方案? 例如,在原始 position 中保留2 bits
並隨機更改第3rd bit
接近2bits
。 It is important for me to keep 3bits on among 39bits
。 我想做一個控制突變,目的是產生一個小的變化。
我的目標是make small changes
,因為每bit
都代表一個location
。 突變的目的是進行小的更改並查看評估結果。 因此,代碼應該做這樣的事情。 As for CS1:
(111000000000000000000000000000000000000)
, I want something like (011010000000000000000000000000000000000)
, or (011001000000000000000000000000000000000)
, or (010110000000000000000000000000000000000)
or (101010000000000000000000000000000000000)
, or (00101100000000000000000000000000000000)
, etc
要實現變異,有什么好方法可以將當前位置隨機更改為其他位置,保持范圍僅在 1-39 個位置之間(限制)?
你可以使用 numpy 並做類似的事情
import numpy
s = "1110000000000000000000000000"
def mutate(s):
arr = numpy.array(list(s))
mask = arr == "1"
indices_of_ones = numpy.argwhere(mask).flatten()
pick_one_1_index = numpy.random.choice(indices_of_ones)
potential_swaps = numpy.argwhere(~mask).flatten()
distances = numpy.abs(pick_one_1_index - potential_swaps)
probabilities = (1/distances) # higher probabilities the less distance from its original position
# probabilities = (1/(distances*2)) # even higher probabilities the less distance from its original position
pick_one_0_index = numpy.random.choice(potential_swaps,p=probabilities/probabilities.sum())
arr[pick_one_1_index] = '0'
arr[pick_one_0_index] = '1'
return "".join(arr)
可能有更優的解決方案
或者,您可以為距離添加標量或冪,以對距離進行更多懲罰...
如果你想測試不同的乘數或冪的概率,你可以使用類似
def score_solution(s1,s2):
ix1 = set([i for i,v in enumerate(s1) if v == "1"])
ix2 = set([i for i,v in enumerate(s2) if v == "1"])
a,b = ix1 ^ ix2
return numpy.abs(a-b)
def get_solution_score_quantiles(sample_size=100,quantiles = [0.25,0.5,0.75]):
scores = []
for i in range(10):
s1 = mutate(s)
scores.append(score_solution(s,s1))
return numpy.quantile(scores,quantiles)
print(get_solution_score_quantiles(50))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.