0

So I am having some trouble with my code.

Essentially, I am creating an initial array (x0x1) of random coordinates (this is successful). Then, I want to generate a candidate coordinate vector (z) from 3 random choice coordinate vectors from my original coordinate array. I then compare f(z) with every pair of coordinates f(x0x1[i]) in my original array. If f(z) is lower, then I take it to a new array of coordinates. The cycle repeats until I find the value of z that minimizes my function.

The error I get is : index 1 is out of bounds for axis 0 with size 1, and it seems to be happening in my calculateFunction method. Not sure why.

Here is the code I am working with:

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()   

The error trace is the following:

   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
13
  • Paste the full error and traceback. Commented Nov 13, 2021 at 8:59
  • Based on the full error message identify exactly which line has the problem (no seems allowed :) ). Then check the shape of the variable indexed. Commented Nov 13, 2021 at 9:08
  • 1
    So you need to examine x. The error says that x[1] is wrong. Look up the stack, the newPopulationArray[i] looks suspicious. Is that really a size 2 array? Commented Nov 13, 2021 at 9:21
  • 1
    Is it really? Have you checked? Or are you just assuming or hopeing? Commented Nov 13, 2021 at 9:23
  • 1
    Also, 5(x[1]-x[0]**2) in calculateFunctionValue isn't multiplication by 5 Commented Nov 13, 2021 at 9:24

1 Answer 1

1

These 2 lines in x0x1Array function do not generate arrays of the same shape.

 x0x1 = np.zeros((N-1, 1), dtype=float) // shape is (49, 1)
 x0x1 = np.array((x0,x1)).T // shape is (1, 49, 2)

You should revisit the second line to create that array in a proper way.

UPDATE: getting 3 pairs from the list:

x0_ind, x1_ind, x2_ind = np.random.choice(lennewPopulationArray), 3)
x0 = newPopulationArray[x0_ind]
x1 = newPopulationArray[x1_ind]
x2 = newPopulationArray[x2_ind]

Also, in the calculateFunctionValue function add multiplication sign after the 5 so python knows to multiply

Sign up to request clarification or add additional context in comments.

17 Comments

That definitely explains why x[1] is out of bound.
@WeightliftingWithoutLimits any chance you will log X in your function to explicitly show what is going wrong with your code?
@WeightliftingWithoutLimits the selection of your x0, x1 and x2 also seems not correct. you want to select random 3 pairs from the x0x1 array right? the current code is just selecting 3 indexes, but not the pairs themselves
Many thanks buddy! I will look at this. I will be back if I still have problems with this code.
You are welcome. Also, to avoid such confusions, use IDEs such as PyCharm or Visual Code. They do code analysis and help you understand what is wrong with your code. Also, try learning debugging, that is an amazing tool for such cases.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.