for i in range(pN): for j in range(dim): V[i][j] = random.uniform(0, 1) if j == 2: X[i][j] = random.uniform(DOWN[j], UP[j])#随机生成在x,y之间的数 else: X[i][j] = round(random.randint(DOWN[j], UP[j]), 0) pbest[i] = X[i] le, pred, y_t = training(X[i]) NN = 1 # 计算适应值 tmp = function(pred, y_t, le) p_fit[i] = tmp if tmp > fit: fit = tmp gbest = X[i] print("初始全局最优参数:{:}".format(gbest)) fitness = [] # 适应度函数 for j in range(MAX_EP_STEPS): fit2 = [] plt.title("第{}次迭代".format(i_episode)) for i in range(pN): le, pred, y_t = training(X[i]) temp = function(pred, y_t, le) fit2.append(temp / 1000) if temp > p_fit[i]: # 更新个体最优 p_fit[i] = temp pbest[i] = X[i] if p_fit[i] > fit: # 更新全局最优 gbest = X[i] fit = p_fit[i] print("搜索步数:{:}".format(j)) print("个体最优参数:{:}".format(pbest)) print("全局最优参数:{:}".format(gbest)) for i in range(pN): V[i] = w * V[i] + c1 * random.uniform(0, 1) * (pbest[i] - X[i]) + c2 * random.uniform(0, 1) * ( gbest - X[i]) ww = 1 for k in range(dim): if DOWN[k] < X[i][k] + V[i][k] < UP[k]: continue else: ww = 0 X[i] = X[i] + V[i] * ww fitness.append(fit)
时间: 2023-05-15 11:05:09 浏览: 154
这段代码是一个双重循环,第一个循环变量是i,范围是0到pN-1,第二个循环变量是j,范围是0到dim-1。在循环中,使用random.uniform(0,1)生成一个0到1之间的随机数,并将其赋值给V[i][j]。如果j等于2,则使用random.uniform(DOWN[j],UP[j])生成一个DOWN[j]到UP[j]之间的随机数,并将其赋值给X[i][j]。
相关问题
用列表推导式和生成式改写下面这段代码def monte_carlo(dim, N): v = 1 for i in range(dim): v *= 2 s = 0 for i in range(N): x = [random.uniform(0,1) for j in range(dim)] s += f(x) return s * v / N
可以这样改写:
v = 2 ** dim
s = sum(f([random.uniform(0, 1) for _ in range(dim)]) for _ in range(N))
result = s * v / N
使用生成式:
v = 2 ** dim
s = sum(f([random.uniform(0, 1) for _ in range(dim)]) for i in range(N))
result = s * v / N
使用列表推导式:
v = 2 ** dim
s = sum([f([random.uniform(0, 1) for j in range(dim)]) for i in range(N)])
result = s * v / N
def generate_genes(self): genes = [] for i in range(POPULATION_SIZE): gene = { 'x': random.uniform(0, LAND_WIDTH), 'y': random.uniform(0, LAND_HEIGHT), 'height': random.uniform(MIN_HEIGHT, MAX_HEIGHT) } genes.append(gene) return genes怎么缩进
代码缩进应该是这样的:
```
def generate_genes(self):
genes = []
for i in range(POPULATION_SIZE):
gene = {
'x': random.uniform(0, LAND_WIDTH),
'y': random.uniform(0, LAND_HEIGHT),
'height': random.uniform(MIN_HEIGHT, MAX_HEIGHT)
}
genes.append(gene)
return genes
```
在 Python 中,缩进非常重要,因为它用于表示代码块的开始和结束。在这个例子中,`generate_genes` 函数和 `for` 循环的代码块都需要缩进。同时,字典的定义也需要缩进,并且每行键值对之间也需要缩进。
阅读全文