|
| 1 | +import tensorflow as tf |
| 2 | +import tensorflow.keras |
| 3 | +import pygad.kerasga |
| 4 | +import pygad |
| 5 | +import numpy |
| 6 | + |
| 7 | +def fitness_func(ga_instanse, solution, sol_idx): |
| 8 | + global train_data, data_outputs, keras_ga, model |
| 9 | + |
| 10 | + predictions = pygad.kerasga.predict(model=model, |
| 11 | + solution=solution, |
| 12 | + data=train_data) |
| 13 | + |
| 14 | + cce = tensorflow.keras.losses.CategoricalCrossentropy() |
| 15 | + solution_fitness = 1.0 / (cce(data_outputs, predictions).numpy() + 0.00000001) |
| 16 | + |
| 17 | + return solution_fitness |
| 18 | + |
| 19 | +def on_generation(ga_instance): |
| 20 | + print("Generation = {generation}".format(generation=ga_instance.generations_completed)) |
| 21 | + print("Fitness = {fitness}".format(fitness=ga_instance.best_solution(ga_instance.last_generation_fitness)[1])) |
| 22 | + |
| 23 | +# The dataset path. |
| 24 | +dataset_path = r'../data/Skin_Cancer_Dataset' |
| 25 | + |
| 26 | +num_classes = 2 |
| 27 | +img_size = 224 |
| 28 | + |
| 29 | +# Create a simple CNN. This does not gurantee high classification accuracy. |
| 30 | +model = tf.keras.models.Sequential() |
| 31 | +model.add(tf.keras.layers.Input(shape=(img_size, img_size, 3))) |
| 32 | +model.add(tf.keras.layers.Conv2D(32, (3,3), activation="relu", padding="same")) |
| 33 | +model.add(tf.keras.layers.MaxPooling2D((2, 2))) |
| 34 | +model.add(tf.keras.layers.Flatten()) |
| 35 | +model.add(tf.keras.layers.Dropout(rate=0.2)) |
| 36 | +model.add(tf.keras.layers.Dense(num_classes, activation="softmax")) |
| 37 | + |
| 38 | +# Create an instance of the pygad.kerasga.KerasGA class to build the initial population. |
| 39 | +keras_ga = pygad.kerasga.KerasGA(model=model, |
| 40 | + num_solutions=10) |
| 41 | + |
| 42 | +train_data = tf.keras.utils.image_dataset_from_directory( |
| 43 | + directory=dataset_path, |
| 44 | + image_size=(img_size, img_size), |
| 45 | + label_mode="categorical", |
| 46 | + batch_size=32 |
| 47 | +) |
| 48 | + |
| 49 | +# Get the dataset labels. |
| 50 | +# train_data.class_indices |
| 51 | +data_outputs = numpy.array([]) |
| 52 | +for x, y in train_data: |
| 53 | + data_outputs = numpy.concatenate([data_outputs, numpy.argmax(y.numpy(), axis=-1)]) |
| 54 | +data_outputs = tf.keras.utils.to_categorical(data_outputs) |
| 55 | + |
| 56 | +# Check the documentation for more information about the parameters: https://pygad.readthedocs.io/en/latest/README_pygad_ReadTheDocs.html#pygad-ga-class |
| 57 | +initial_population = keras_ga.population_weights # Initial population of network weights. |
| 58 | + |
| 59 | +# Create an instance of the pygad.GA class |
| 60 | +ga_instance = pygad.GA(num_generations=10, |
| 61 | + num_parents_mating=5, |
| 62 | + initial_population=initial_population, |
| 63 | + fitness_func=fitness_func, |
| 64 | + on_generation=on_generation) |
| 65 | + |
| 66 | +# Start the genetic algorithm evolution. |
| 67 | +ga_instance.run() |
| 68 | + |
| 69 | +# After the generations complete, some plots are showed that summarize how the outputs/fitness values evolve over generations. |
| 70 | +ga_instance.plot_fitness(title="PyGAD & Keras - Iteration vs. Fitness", linewidth=4) |
| 71 | + |
| 72 | +# Returning the details of the best solution. |
| 73 | +solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness) |
| 74 | +print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness)) |
| 75 | +print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx)) |
| 76 | + |
| 77 | +predictions = pygad.kerasga.predict(model=model, |
| 78 | + solution=solution, |
| 79 | + data=train_data) |
| 80 | +# print("Predictions : \n", predictions) |
| 81 | + |
| 82 | +# Calculate the categorical crossentropy for the trained model. |
| 83 | +cce = tensorflow.keras.losses.CategoricalCrossentropy() |
| 84 | +print("Categorical Crossentropy : ", cce(data_outputs, predictions).numpy()) |
| 85 | + |
| 86 | +# Calculate the classification accuracy for the trained model. |
| 87 | +ca = tensorflow.keras.metrics.CategoricalAccuracy() |
| 88 | +ca.update_state(data_outputs, predictions) |
| 89 | +accuracy = ca.result().numpy() |
| 90 | +print("Accuracy : ", accuracy) |
| 91 | + |
| 92 | +# model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) |
| 93 | + |
| 94 | +# _ = model.fit(x, y, verbose=0) |
| 95 | +# r = model.predict(data_inputs) |
0 commit comments