Beispiel #1
0
    def Fit(self, dataset):
        t = Timer()
        t.AddTime("Start")
        self.dataset = dataset

        self.kmeans.fit(dataset)

        print('DEBUG - KMeans Centroids:')
        print(self.kmeans.cluster_centers_)

        t.AddTime("End")

        t.PrintTimes()
Beispiel #2
0
    def Fit(self, dataset):
        """ Calcula la mejor distribución de los puntos del dataset, según los parámetros elegidos."""
        t = Timer()

        wx.CallAfter(self.listener.SetMaxRange, self.NIterations)

        t.AddTime("Start")
        self.dataset = dataset
        self.datasetLen, self.datasetDimension = list(dataset.shape)

        self.population = self._GetInitialPop(
        )  # 1. Generación de población inicial

        t.AddTime("Initial pop")

        self.bestIndividual = None

        for it in range(self.NIterations):
            self.fitness = [i.Fitness() for i in self.population
                            ]  # 2. Calculo de aptitud de la población

            minFit = np.argmax(self.fitness)
            print('DEBUG - Min fit key %d - value: %f' %
                  (minFit, self.fitness[minFit]))

            # if (self.fitness[minFit] <= self.FITNESS_THRESHOLD): # 3. Primera condición de parada
            #     self.bestIndividual = self.population[minFit]
            #     break

            newPop = []  # Construcción de la nueva población

            # 4. Selección de individuos. Elitista + Ruleta

            # Aseguro al mejor miembro de la población
            eliteInd = self._ElitistSelection()
            newPop.append(eliteInd)

            # Selecciona el resto por ruleta

            selectionAmount = int(len(self.population) * self.SELECTION_RATIO)

            print('DEBUG - Selection amount: %s' % selectionAmount)

            selected = self._WheelSelection(selectionAmount -
                                            1)  # Porque ya tengo uno de elite
            newPop.extend(selected)

            # 5. Cruza pares de individuos seleccionados al azar

            crossAmount = int(
                len(self.population) * self.CROSSING_RATIO
            )  # Cantidad de individuos resultados de la cruza

            print('DEBUG - Crossing amount: %s' % crossAmount)

            crossOverflow = crossAmount % 2.0
            crossAmount = int(math.ceil(
                crossAmount /
                2.0))  # Se usa la mitad de pares para generar 2 hijos

            print('DEBUG - Overflow: %s' % crossOverflow)
            print('DEBUG - Cross: %s' % crossAmount)

            toCross = self._GetCrossingPairs(crossAmount)  # Selección de pares

            for pair in toCross:
                child1, child2 = pair[0].CrossWith(pair[1])  # Cruza
                newPop.append(child1)
                newPop.append(child2)

            # 6. Mutación de individuos seleccionados al azar

            mutationAmount = int(len(self.population) * self.MUTATION_RATIO)

            # Si se obtuvo un individuo extra en la cruza resto uno para mutar
            if crossOverflow > 0:
                mutationAmount -= 1

            print('DEBUG - Mutation amount: %s' % mutationAmount)

            mutated = self._GetMutated(mutationAmount)

            newPop.extend(mutated)

            # El método anterior no asegura individuos mutados por lo tanto
            # se completa la población con nuevas cruzas si es necesario
            if (len(newPop) < len(self.population)):
                missingPop = len(self.population) - len(newPop)

                toCross = self._GetCrossingPairs(missingPop)

                for pair in toCross:
                    child1, child2 = pair[0].CrossWith(pair[1])

                    newPop.append(child1)

                    if (len(newPop) == len(self.population)):
                        break

                    newPop.append(child2)

                    if (len(newPop) == len(self.population)):
                        break

            print("New pop lenght: %d" % len(newPop))

            self.population = newPop

            t.AddTime("Iteration %d" % it)

            wx.CallAfter(self.listener.UpdateProgress, it)

        # 7. Ultima condición de parada, fin de las iteraciones
        # Si no encontré una solución antes, uso la mejor despues del proceso
        if self.bestIndividual is None:
            minFit = np.argmax(self.fitness)
            self.bestIndividual = self.population[minFit]

        t.AddTime("End")

        t.PrintTimes()

        print('DEBUG - Fitness: %s' % self.fitness[minFit])