我在运行此代码时获得TypeError: slice indices must be integers or None or have an __index__ method
。问题是它在python 3.5.2(conda)上工作正常但是在python 3.6.1(conda)上它会出现这个错误。
任何人都知道如何更改它以使其适用于这两个版本?或者至少是新人?
import numpy as np
import random
import math
def geneticAlgorithm(f, x_min, x_max, cel, popSize, pMut, maxIter):
result = {
'x_opt': None,
'f_opt': None,
'x_hist': [],
'f_hist': [],
'f_mean': []
}
# Check the number of dimensions
Dim = len(x_min)
# Initialize Population
population = np.full((popSize, cel*Dim), None)
for i in range(popSize):
population[i,:] = np.random.uniform(cel*Dim)<0
coordinates = getCoordinates(population, cel, x_min, x_max, pMut)
# Calculate fittness of individuals
objFunction = [None]*popSize
for i in range(popSize):
objFunction[i] = f(coordinates[i,:])
# Assign the first population to output
result['x_opt'] = coordinates[np.argmin(objFunction),]
result['f_opt'] = f(coordinates[np.argmin(objFunction),])
# The generational loop
finished = False
currIter = 1
while(finished == False):
# Assign the output
if currIter <= maxIter:
if result['f_opt'] > f(coordinates[np.argmin(objFunction),]):
result['x_opt']= coordinates[np.argmin(objFunction),]
result['f_opt']= f(coordinates[np.argmin(objFunction),])
result['f_hist'].append(result['f_opt'])
result['x_hist'].append(coordinates[np.argmin(objFunction)])
result['f_mean'].append(np.mean(objFunction))
else: finished = True
# Translate binary coding into real values
coordinates = getCoordinates(population, cel, x_min, x_max, pMut)
# Calculate fittness of the individuals
objFunction = [None]*popSize
for i in range(popSize):
objFunction[i] = f(coordinates[i,:])
rFitt = min(objFunction)/objFunction # Relative Fittness
nrFitt = rFitt / sum(rFitt) # Relative Normalized (sum up to 1) Fittness
# Selection operator (Roulette wheel)
selectedPool = [0] * popSize
for i in range(popSize):
selectedPool[i] = sum(np.random.uniform()>np.cumsum(nrFitt))+1 #znowu runif i cumsum
# Crossover operator (for selected pool)
nextGeneration = np.full((popSize, cel*Dim), None)
for i in range(1, popSize):
parentId = np.round(random.uniform(1,popSize))
cutId = np.round(random.uniform(1,Dim*cel-1)) # Please, do not exceed the matrix sizes
nextGeneration[i, 0:int(cutId)] = population[selectedPool[i]-1, 0:int(cutId)]
nextGeneration[i, (cutId): (Dim*cel)] = population[selectedPool[int(parentId)-1]-1, (cutId) : (Dim*cel)]
# Mutation operator
for i in range(popSize):
arr=np.arange(Dim*cel)
test1=np.random.uniform(size=Dim*cel)>pMut
genomeMutId = arr[np.where(test1)] # Draw the genomes that will mutate
for j in range(len(genomeMutId)):
nextGeneration[i, genomeMutId[j]] = not(nextGeneration[i, genomeMutId[j]])
# Replace the old population
population = nextGeneration
currIter = currIter + 1
return(result)
def intbin(x):
# # Translate the binary coding to real values numbers
b = [2**(idx+1) for idx, v in enumerate(x) if v]
return sum(b)
def getCoordinates(population, cel, x_min, x_max, pMut):
# Transform the binary coding into coordinates
coordinates = np.full((population.shape[0], 2), 0)
for i in range(population.shape[0]):
for j in range(2):
s1=cel*(j)+1
s2=(j+1)*cel
coordinatesTemp = intbin(population[i, range(s1,s2)])
coordinates[i,j] = ((x_max[j]-x_min[j])/(2**cel-1))*coordinatesTemp+x_min[j]
return(coordinates)
xSeed = (3, 4)
n_grid = 100
ub_iter = 100
def myFun(x) :
return ( 0.6 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )
ga = geneticAlgorithm(myFun, (-20, -20), (20, 20), cel=50, popSize = 30, maxIter = ub_iter, pMut = 0.05)
print(ga)
所以我使用jupyter和python 3.6.1运行此代码并且它不起作用。它在c9.io(即python 3)上运行fin,在另一台PC上运行jupyter上的旧版本3.5.2。这里的问题似乎是这里的问题:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-71595b494779> in <module>()
167 return ( 0.6 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) )
168
--> 169 ga = geneticAlgorithm(myFun, (-20, -20), (20, 20), cel=50, popSize = 30, maxIter = ub_iter, pMut = 0.05)
170
171 print(ga)
<ipython-input-1-71595b494779> in geneticAlgorithm(f, x_min, x_max, cel, popSize, pMut, maxIter)
108 #print(selectedPool[int(parentId)-1])
109 nextGeneration[i, 0:int(cutId)] = population[selectedPool[i]-1, 0:int(cutId)]
--> 110 nextGeneration[i, (cutId): (Dim*cel)] = population[selectedPool[int(parentId)-1]-1, (cutId) : (Dim*cel)]
111
112
TypeError: slice indices must be integers or None or have an __index__ method