File size: 5,930 Bytes
d729bee 6182e9b d729bee 6182e9b d729bee 6182e9b d729bee 6cd1499 6182e9b d729bee 6182e9b d729bee 6cd1499 852ea5a d729bee 6182e9b d729bee 6182e9b d729bee 6182e9b d729bee 6182e9b d729bee 6182e9b e8fae83 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
import tensorflow as tf
import pygad
import numpy
from imageMulticlassClassification import ImageMulticlassClassification
def fitness_func(ga_instance, solution, solution_idx):
try:
print("solution_idx :", solution_idx)
print("solution :", solution)
neuronDense1 = [16, 32, 64, 128, 256, 512, 1024, 2048]
neuronDense2 = [16, 32, 64, 128, 256, 512, 1024, 2048]
Dropout1 = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
Dropout2 = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
Batchs = [16, 32, 64, 128, 256, 512, 1024, 2048]
Activations = ["relu", "sigmoid", "softplus", "softsign", "tanh", "selu", "gelu", "linear"]
Optimizers = ["Adam", "RMSprop", "SGD", "Adadelta", "Adagrad", "Adamax", "Ftrl", "Nadam"]
LossFunction = ["SparseCategoricalCrossentropy", "CategoricalCrossentropy", "BinaryCrossentropy", "MeanAbsoluteError", "MeanSquaredError", "SquaredHinge", "CategoricalHinge", "CosineSimilarity"]
# Use the 'solution' array to access the genes.
usedNeuronDense1 = neuronDense1[solution[0]]
usedNeuronDense2 = neuronDense2[solution[1]]
usedDropout1 = Dropout1[solution[2]]
usedDropout2 = Dropout2[solution[3]]
usedBatchs = Batchs[solution[4]]
usedActivations = Activations[solution[5]]
usedOptimizers = Optimizers[solution[6]]
usedLossFunction = LossFunction[solution[7]]
imgWidth = 50
imgHeight = 50
batchSize = usedBatchs
IMC = ImageMulticlassClassification(imgWidth, imgHeight, batchSize)
IMC.data_MakeDataset(datasetUrl="https://huggingface.co/datasets/S1223/HandGestureDataset/resolve/main/HandGestureDataset.tgz", datasetDirectoryName="HandGestureDataset", ratioValidation=0.20)
IMC.data_PreprocessingDataset()
customModel = tf.keras.Sequential()
customModel.add(tf.keras.layers.Conv2D(16, (3, 3), input_shape=(imgWidth, imgHeight, 3), activation=usedActivations))
customModel.add(tf.keras.layers.Conv2D(16, (3, 3), activation=usedActivations))
customModel.add(tf.keras.layers.Dropout(usedDropout1))
customModel.add(tf.keras.layers.MaxPooling2D((2, 2)))
customModel.add(tf.keras.layers.Flatten())
customModel.add(tf.keras.layers.BatchNormalization())
customModel.add(tf.keras.layers.Dense(usedNeuronDense1, activation=usedActivations))
customModel.add(tf.keras.layers.Dense(usedNeuronDense2, activation=usedActivations))
customModel.add(tf.keras.layers.Dropout(usedDropout2))
customModel.add(tf.keras.layers.Dense(10, activation="softmax"))
IMC.model_make(customModel)
modelName = ""
for x in solution:
modelName += f"{str(x)}_"
IMC.training_model(epochs=50, modelName=modelName, optimizer=usedOptimizers, lossFunction=usedLossFunction)
IMC.evaluation(labelName=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"])
output = float(IMC.history.history["val_accuracy"][-1])
fitness = output
return fitness
except Exception as e:
print(str(e))
return 0.00001
function_inputs = [1, 2, 3, 4, 5, 6, 7, 8]
desired_output = 5
num_generations = 1
num_parents_mating = 4
sol_per_pop = 10
num_genes = len(function_inputs)
init_range_low = 0
init_range_high = 8
parent_selection_type = "rws"
keep_parents = 1
crossover_type = "single_point"
mutation_type = "swap"
mutation_percent_genes = 'default'
ga_instance = pygad.GA(num_generations=num_generations,
num_parents_mating=num_parents_mating,
fitness_func=fitness_func,
sol_per_pop=sol_per_pop,
num_genes=num_genes,
init_range_low=init_range_low,
init_range_high=init_range_high,
parent_selection_type=parent_selection_type,
keep_parents=keep_parents,
crossover_type=crossover_type,
mutation_type=mutation_type,
mutation_percent_genes=mutation_percent_genes,
gene_type=[int, int, int, int, int, int, int, int],
allow_duplicate_genes=False,
save_best_solutions=False,
save_solutions=False)
print("Initial Population")
print(ga_instance.initial_population)
print(ga_instance.run())
solution, solution_fitness, solution_idx = ga_instance.best_solution()
print("Parameters of the best solution : {solution}".format(solution=solution))
print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))
import subprocess
import sys
# Function to install required packages
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
# List of required packages for the script
required_packages = ['os', 'shutil', 'zipfile']
# Check if the required packages are installed, if not, install them
for package in required_packages:
try:
__import__(package)
except ImportError:
install(package)
import os
import shutil
import zipfile
# Create a new directory to store the files
folder_name = 'data'
if not os.path.exists(folder_name):
os.makedirs(folder_name)
# Move all .xlsx and .png files to the new directory
for file in os.listdir('.'):
if file.endswith('.xlsx') or file.endswith('.png') or file.endswith('.out'):
shutil.move(file, os.path.join(folder_name, file))
# Zip the folder
zipf = zipfile.ZipFile('data.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(folder_name):
for file in files:
zipf.write(os.path.join(root, file), arcname=file)
zipf.close()
print("All .xlsx and .png files have been moved and zipped into data.zip")
|