我正在研究一個優化問題。我有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 個位置中的三個位置(限制)。假設我想把我的救護車放在5th, 19th, and 31 positions.-- Chromosome 1= [000010000000000000100000000000100000000]。在上述介紹中,I am turning on 5-bit, 19-bit, and 31-bit.
是否可以翻轉一點接近原始解決方案?例如,保持2 bits在原來的位置,隨機改變3rd bitclose to 2bits。It is important for me to keep 3bits on among 39bits. 我想做一個控制突變,目的是產生一個小的變化。
我的目標是make small changes因為每個bit代表一個location. 突變的目的是進行小的更改并查看評估結果。因此,代碼應該做這樣的事情。As for CS1: (111000000000000000000000000000000000000), 我想要類似(011010000000000000000000000000000000000), 或(011001000000000000000000000000000000000),(010110000000000000000000000000000000000)或(101010000000000000000000000000000000000), 或(00101100000000000000000000000000000000), 等
為了實作突變,有什么好方法可以將當前位置隨機更改為其他位置,保持范圍僅在 1-39 個位置之間(限制)?
uj5u.com熱心網友回復:
你可以使用 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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/512350.html
下一篇:如何使用for回圈回傳串列中“movie”=[“spiderman”、“endgame”、“justiceleague”、“batman”]的值
