Why is it showing 'invalid syntax' when I am trying to run a genetic programming code using deap library?

73 Views Asked by At

After calling all required modules, I assined all the operators and created Fitness and Individual. After that Evaluation function was defined and toolbox was registered as follows:

# Define the fitness function for evaluating candidate kernels
def evaluate_kernel(individual):
    # Compile the kernel expression as a callable function
    kernel_func = gp.compile(individual, pset)
    # Train an SVM with the k`your text`ernel function and compute its accuracy on the validation set
    svm = SVC(kernel=kernel_func)
    svm.fit(X_train, y_train)
    accuracy = svm.score(X_val, y_val)
    return accuracy,
toolbox = base.Toolbox()
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=3)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate_kernel)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("mutate", gp.mutUniform, pset=pset)
toolbox.register("select", tools.selTournament, tournsize=3)

# Define main function
def main():
    import numpy
    pop = toolbox.population(n=50)
    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=10, stats=stats, halloffame=hof, verbose=True)

    return pop, logbook, hof

# Calling main function
if __name__ == "__main__":
    pop, log, hof = main()
    print("Best individual is: %s\nwith fitness: %s" % (hof[0], hof[0].fitness))
    print(pop)`

But I am getting this error: Traceback (most recent call last):

  File "/usr/local/lib/python3.9/dist-packages/IPython/core/interactiveshell.py", line 3553, in run_code
  exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-26-9a5248fbca23>", line 2, in <cell line: 1>
    pop=main()

1 frames
  File "/usr/local/lib/python3.9/dist-packages/deap/algorithms.py", line 151, in eaSimple
    for ind, fit in zip(invalid_ind, fitnesses):

  File "<ipython-input-21-421003e68116>", line 4, in evaluate_kernel
    kernel_func = gp.compile(individual, pset)

  File "/usr/local/lib/python3.9/dist-packages/deap/gp.py", line 480, in compile
    return eval(code, pset.context, {})

  File "<string>", line 1
    lambda ARG0: [<deap.gp.Primitive object at 0x7ffa7a7cb540>, <deap.gp.Primitive object at 0x7ffa7a7cb900>, <deap.gp.Terminal object at 0x7ffa7b3aaa00>, <deap.gp.Terminal object at 0x7ffa7b3aaa00>]
                  ^
SyntaxError: invalid syntax

Any idea how to correct the error? Thank you in advance

0

There are 0 best solutions below