射水鱼算法(AHO)Python实现的数组赋值与索引问题
射水鱼算法(AHO)代码报错解决方案
错误根源分析
TypeError: object of type 'numpy.float64' has no len():传入equation_3/equation_5的参数是标量而非d维数组,根源是种群数组X维度定义错误,导致赋值时类型不匹配,后续传递参数变成标量。ValueError: setting an array element with a sequence:尝试将d维数组赋值给标量位置(原X[i,t]是单个数值),因为X初始化为(N, Itermax),无法容纳d维位置向量。
修正后的完整代码
import numpy as np def equation_3(Xk_t, omega, theta, delta): d = Xk_t.shape[0] # 用numpy数组shape属性获取维度,替代len random_position = np.random.randint(0, d) new_position = np.zeros(d) new_position[random_position] = omega * np.sin(2 * theta) return Xk_t + new_position + delta def equation_5(Xi_t, omega, theta, delta): d = Xi_t.shape[0] # 用numpy数组shape属性获取维度,替代len random_positions = np.random.choice(range(d), 2, replace=False) new_position = np.zeros(d) new_position[random_positions] = omega * np.sin(2 * theta) return Xi_t + new_position + delta def equation_6(alpha): # 实现AHO算法中theta_0的生成逻辑,返回[-alpha, alpha]范围内的随机角度 return np.random.uniform(-alpha, alpha) def AHO(d, domains, f, theta, omega, N, Itermax, alpha, xmin, xmax): # 修正种群数组维度:N个个体,Itermax个迭代时刻,每个个体存储d维位置向量 X = np.zeros((N, Itermax, d)) # 初始化t=0时刻的种群初始位置 for i in range(N): X[i, 0] = np.random.uniform(xmin, xmax, size=d) # 迭代从t=1到t=Itermax-1,避免索引越界 for t in range(1, Itermax): for i in range(N): theta_0 = equation_6(alpha) # 修正角度范围判断逻辑 if (0 < abs(theta_0) < theta) or (np.pi - theta < abs(theta_0) < np.pi): # 基于个体前一时刻位置更新,而非重新生成随机位置(符合AHO算法逻辑) Xk_t = X[i, t-1] delta = np.random.uniform(-1, 1, size=d) X[i, t] = equation_3(Xk_t, omega, theta, delta) else: # 补充else分支逻辑,调用equation_5更新位置 Xi_t = X[i, t-1] delta = np.random.uniform(-1, 1, size=d) X[i, t] = equation_5(Xi_t, omega, theta, delta) # 此处可添加适应度计算与最优解更新逻辑 # fitness = f(X[i, t]) # ... return X
关键修正点说明
- 种群数组维度修正:将
X从(N, Itermax)改为(N, Itermax, d),确保每个个体的位置以d维数组存储,解决赋值不匹配问题。 - 维度获取方式优化:用
Xk_t.shape[0]替代len(Xk_t),更适配numpy数组的操作习惯,避免类型判断错误。 - 种群初始化补充:添加t=0时刻的种群初始位置生成,完善算法迭代的起始逻辑。
- 位置更新逻辑修正:基于个体前一时刻位置进行更新(而非重新生成随机位置),符合AHO算法的迭代进化逻辑。
- 分支逻辑补全:补充else分支调用
equation_5的逻辑,确保所有个体的位置都能得到更新。
内容的提问来源于stack exchange,提问作者Ahmed Ehab
相关产品推荐
相关产品推荐

