[英]Having problems with an index error (Python)
所以我的代码有一些问题。
本质上,我正在创建一个随机坐标的初始数组(x0x1)(这是成功的)。 然后,我想从原始坐标数组中的 3 个随机选择坐标向量生成一个候选坐标向量 (z)。 然后我将 f(z) 与原始数组中的每对坐标 f(x0x1[i]) 进行比较。 如果 f(z) 较低,那么我将它带到一个新的坐标数组。 循环重复,直到我找到最小化我的函数的 z 值。
我得到的错误是:索引 1 超出了大小为 1 的轴 0 的范围,这似乎发生在我的 calculateFunction 方法中。 不知道为什么。
这是我正在使用的代码:
import numpy as np
import numpy.random
def calculateFunctionValue(x):
return (x[0]-1)**2+5(x[1]-x[0]**2)**2
def x0x1Array(N, F, K):
x0x1 = np.zeros((N-1, 1), dtype=float)
x0 = np.zeros((N-1, 1), dtype=float)
x1 = np.zeros((N-1, 1), dtype=float)
for i in range(0, len(x0)):
for j in range(0, len(x1)):
x0[i] = np.random.uniform(-2,2)
x1[j] = np.random.uniform(-2,2)
x0x1 = np.array((x0,x1)).T
generateCandidateVector(x0x1, N, F, K)
def generateCandidateVector(newPopulationArray, N, F, K):
x0 = np.zeros((1,2))
x1 = np.zeros((1,2))
x2 = np.zeros((1,2))
populationOneArray = np.zeros((N-1, 1))
generation = 0
while generation <= K:
generation = generation + 1
for i in range(0, N-1):
x0 = np.random.choice(len(newPopulationArray), 1)
x1 = np.random.choice(len(newPopulationArray), 1)
x2 = np.random.choice(len(newPopulationArray), 1)
vectorZ = x0 + F*(x1-x2)
if(calculateFunctionValue(vectorZ) < calculateFunctionValue(newPopulationArray[i])):
vectorZ = newPopulationArray[i]
print(vectorZ)
return generateCandidateVector(vectorZ)
elif(calculateFunctionValue(vectorZ) > calculateFunctionValue(newPopulationArray[i])):
vectorZ = populationOneArray[i]
def main():
K = 50
F = 0.8
N=50
x0x1Array(N, F, K)
main()
错误跟踪如下:
runfile('C:/Users/SPNMo/Documents/untitled5.py', wdir='C:/Users/SPNMo/Documents')
[0]
C:\Users\SPNMo\Documents\untitled5.py:17: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
return (x[0]-1)**2+5(x[1]-x[0]**2)**2
Traceback (most recent call last):
File "C:\Users\SPNMo\Documents\untitled5.py", line 74, in <module>
main()
File "C:\Users\SPNMo\Documents\untitled5.py", line 71, in main
x0x1Array(N, F, K)
File "C:\Users\SPNMo\Documents\untitled5.py", line 35, in x0x1Array
generateCandidateVector(x0x1, N, F, K)
File "C:\Users\SPNMo\Documents\untitled5.py", line 55, in generateCandidateVector
if(calculateFunctionValue(vectorZ) < calculateFunctionValue(newPopulationArray[i])):
File "C:\Users\SPNMo\Documents\untitled5.py", line 17, in calculateFunctionValue
return (x[0]-1)**2+5(x[1]-x[0]**2)**2
IndexError: index 1 is out of bounds for axis 0 with size 1
x0x1Array 函数中的这两行不会生成相同形状的数组。
x0x1 = np.zeros((N-1, 1), dtype=float) // shape is (49, 1)
x0x1 = np.array((x0,x1)).T // shape is (1, 49, 2)
您应该重新访问第二行以正确的方式创建该数组。
更新:从列表中获取 3 对:
x0_ind, x1_ind, x2_ind = np.random.choice(lennewPopulationArray), 3)
x0 = newPopulationArray[x0_ind]
x1 = newPopulationArray[x1_ind]
x2 = newPopulationArray[x2_ind]
另外,在calculateFunctionValue 函数中,在5 之后添加乘号,所以python 知道要乘
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.