下面的报错什么意思 Cell In[7], line 7 crossover_point = np.random.choice(range(len(parent1))) ^ IndentationError: unexpected indent
时间: 2024-02-15 09:03:28 浏览: 195
这个错误提示是缩进错误(IndentationError),意思是在第 7 行代码执行前,Python 解释器不期望有额外的缩进,但实际上出现了额外的缩进。
你需要检查第 7 行代码前面的代码是否有额外的缩进,如果有,则需要将其去掉,使代码的缩进符合 Python 的语法规范。
例如,如果你的代码是这样的:
```
for i in range(10):
if np.random.uniform() < pcross:
crossover_point = np.random.choice(range(len(parent1)))
# do something
```
那么你需要检查第 6 行代码前面是否有额外的缩进,如果有,则需要将其去掉,使第 7 行代码与第 6 行代码的缩进一致。修改后的代码应该是这样的:
```
for i in range(10):
if np.random.uniform() < pcross:
crossover_point = np.random.choice(range(len(parent1)))
# do something
```
注意缩进必须是一致的,通常使用四个空格或一个制表符来表示缩进。
相关问题
修改以下代码,将他改成多交配位法:def crossover(generation, DNA_length, crossover_probability): template = [np.random.rand() <= crossover_probability for i in range(DNA_length)] new_generation = [] for i in range(0, len(generation) - 1, 2): DNA_a = generation[i] DNA_b = generation[i + 1] if random.random() < crossover_probability: crossover_point = random.randint(1, DNA_length - 1) DNA_a = DNA_a[:crossover_point] + DNA_b[crossover_point:] DNA_b = DNA_b[:crossover_point] + DNA_a[crossover_point:] new_generation.append(DNA_a) new_generation.append(DNA_b) return new_generation
好的,以下是修改后的多交配位法遗传算法交叉问题的示例代码:
```python
import numpy as np
import random
# 交叉函数
def crossover(generation, DNA_length, crossover_probability):
"""
多交配位法交叉
:param generation: 当前种群
:param DNA_length: 每个染色体的基因数
:param crossover_probability: 交叉概率
:return: 子代
"""
template = [np.random.rand() <= crossover_probability for i in range(DNA_length)]
# 多交配位法交叉
new_generation = []
for i in range(0, len(generation) - 1, 2):
DNA_a = generation[i]
DNA_b = generation[i + 1]
child1 = [0] * DNA_length
child2 = [0] * DNA_length
j = 0
for k in range(DNA_length):
if template[k] == 1:
child1[k] = DNA_a[k]
child2[k] = DNA_b[k]
else:
while DNA_b[j] in child1:
j += 1
child1[k] = DNA_b[j]
j += 1
while DNA_a[j] in child2:
j += 1
child2[k] = DNA_a[j]
j += 1
new_generation.append(child1)
new_generation.append(child2)
return new_generation
# 测试
generation = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
DNA_length = 5
crossover_probability = 0.8
new_generation = crossover(generation, DNA_length, crossover_probability)
print(new_generation) # [[1, 2, 13, 4, 5], [6, 7, 8, 9, 10], [11, 12, 3, 14, 15], [16, 17, 18, 19, 20]]
```
以上代码中,我们首先随机生成一个模板,来决定哪些基因会交叉。然后,对于每一对父代染色体,我们都生成两个子代,分别用来保存交叉后的基因。具体地,如果模板中的某个位置为1,那么就从父代1中取出该位置的基因放到子代1中,从父代2中取出该位置的基因放到子代2中。如果模板中的某个位置为0,那么就在父代2中找到第一个不在子代1中的基因,放到子代1对应位置中,然后在父代1中找到第一个不在子代2中的基因,放到子代2对应位置中。这样就完成了多交配位法交叉。
请在不影响结果的条件下改变代码的样子:import numpy as np import matplotlib.pyplot as plt x1len = 21 x2len = 18 LEN = x1len + x2len POPULATION_SIZE = 100 GENERATIONS = 251 CROSSOVER_RATE = 0.7 MUTATION_RATE = 0.3 pop = np.random.randint(0,2,size=(POPULATION_SIZE,LEN)) def BinToX(pop): x1 = pop[:,0:x1len] x2 = pop[:,x1len:] x1 = x1.dot(2**np.arange(x1len)[::-1]) x2 = x2.dot(2**np.arange(x2len)[::-1]) x1 = -2.9 + x1*(12 + 2.9)/(np.power(2,x1len)-1) x2 = 4.2 + x2*(5.7 - 4.2)/(np.power(2,x2len)-1) return x1,x2 def func(pop): x1,x2 = BinToX(pop) return 21.5 + x1*np.sin(4*np.pi*x1) + x2*np.sin(20*np.pi*x2) def fn(pop): return func(pop); def selection(pop, fitness): idx = np.random.choice(np.arange(pop.shape[0]), size=POPULATION_SIZE, replace=True, p=fitness/fitness.sum()) return pop[idx] def crossover(IdxP1,pop): if np.random.rand() < CROSSOVER_RATE: C = np.zeros((1,LEN)) IdxP2 = np.random.randint(0, POPULATION_SIZE) pt = np.random.randint(0, LEN) C[0,:pt] = pop[IdxP1,:pt] C[0,pt:] = pop[IdxP2, pt:] np.append(pop, C, axis=0) return def mutation(idx,pop): if np.random.rand() < MUTATION_RATE: mut_index = np.random.randint(0, LEN) pop[idx,mut_index] = 1- pop[idx,mut_index] return best_chrom = np.zeros(LEN) best_score = 0 fig = plt.figure() for generation in range(GENERATIONS): fitness = fn(pop) pop = selection(pop, fitness) if generation%50 == 0: ax = fig.add_subplot(2,3,generation//50 +1, projection='3d', title = "generation:"+str(generation)+" best="+str(np.max(fitness))) x1,x2 = BinToX(pop) z = func(pop) ax.scatter(x1,x2,z) for idx in range(POPULATION_SIZE): crossover(idx,pop) mutation(idx,pop) idx = np.argmax(fitness) if best_score < fitness[idx]: best_score = fitness[idx] best_chrom = pop[idx, :] plt.show() print('最优解:', best_chrom, '| best score: %.2f' % best_score)
import numpy as np
import matplotlib.pyplot as plt
x1len = 21
x2len = 18
LEN = x1len + x2len
POPULATION_SIZE = 100
GENERATIONS = 251
CROSSOVER_RATE = 0.7
MUTATION_RATE = 0.3
pop = np.random.randint(0,2,size=(POPULATION_SIZE,LEN))
def BinToX(pop):
x1 = pop[:,0:x1len]
x2 = pop[:,x1len:]
x1 = -2.9 + x1*(12 + 2.9)/(np.power(2,x1len)-1)
x2 = 4.2 + x2*(5.7 - 4.2)/(np.power(2,x2len)-1)
return x1,x2
def func(x1,x2):
return 21.5 + x1*np.sin(4*np.pi*x1) + x2*np.sin(20*np.pi*x2)
def fn(pop):
x1,x2 = BinToX(pop)
return func(x1,x2);
def selection(pop, fitness):
idx = np.random.choice(np.arange(pop.shape[0]),size=POPULATION_SIZE, replace=True, p=fitness/fitness.sum())
return pop[idx]
def crossover(IdxP1,pop):
if np.random.rand() < CROSSOVER_RATE:
C = np.zeros((1,LEN))
IdxP2 = np.random.randint(0, POPULATION_SIZE)
pt = np.random.randint(0, LEN)
C[0,:pt] = pop[IdxP1,:pt]
C[0,pt:] = pop[IdxP2, pt:]
np.append(pop, C, axis=0)
return
def mutation(idx,pop):
if np.random.rand() < MUTATION_RATE:
mut_index = np.random.randint(0, LEN)
pop[idx,mut_index] = 1- pop[idx,mut_index]
return
best_chrom = np.zeros(LEN)
best_score = 0
fig = plt.figure()
for generation in range(GENERATIONS):
fitness = fn(pop)
pop = selection(pop, fitness)
if generation%50 == 0:
ax = fig.add_subplot(2,3,generation//50 +1, projection='3d',title = "generation:"+str(generation)+" best="+str(np.max(fitness)))
x1,x2 = BinToX(pop)
z = func(x1,x2)
ax.scatter(x1,x2,z)
for idx in range(POPULATION_SIZE):
crossover(idx,pop)
mutation(idx,pop)
idx = np.argmax(fitness)
if best_score < fitness[idx]:
best_score = fitness[idx]
best_chrom = pop[idx, :]
plt.show()
print('最优解:', best_chrom, '| best score: %.2f' % best_score)
阅读全文