Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

knapsack fitness function will cause GA to evaluate to NaN when max_weight_pct < 1.0 #22

Open
iKuba opened this issue Oct 5, 2024 · 0 comments

Comments

@iKuba
Copy link

iKuba commented Oct 5, 2024

def evaluate(self, state: np.ndarray) -> float:
        """Evaluate the fitness of a state vector.

        Parameters
        ----------
        state : np.ndarray
            State array for evaluation. Must be the same length as the weights
            and values arrays.

        Returns
        -------
        float
            Value of fitness function.

        Raises
        ------
        ValueError
            If `state` is not the same size as the weights and values arrays.
        TypeError
            If `state` is not an instance of `np.ndarray`.
        """
        if not isinstance(state, np.ndarray):
            raise TypeError(f"Expected state_vector to be np.ndarray, got {type(state).__name__} instead.")
        if len(state) != len(self.weights):
            raise ValueError("The state_vector must be the same size as the weights and values arrays.")

        total_weight = np.sum(state * self.weights)
        total_value = np.sum(state * self.values)

        if total_weight <= self._w:
            return float(total_value)

        return 0.0

The final line return 0.0 should probably something like return 1e-6 to avoid a 0.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant