-
Notifications
You must be signed in to change notification settings - Fork 282
Bayesian forgiver strategy #1478
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
Open
hodgesmr
wants to merge
9
commits into
Axelrod-Python:dev
Choose a base branch
from
hodgesmr:bayesian-forgiver-strategy
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
3439f0b
create Bayesian Forgiver strategy
hodgesmr afe61cf
added BayesianForgiver to _strategies
hodgesmr c2619eb
ran rebuild_classifier_table.py to update all_classifiers.yml
hodgesmr b341f8c
added Bayesian Forgiver to strategy index
hodgesmr 3ec848a
bayesian forgiver tests
hodgesmr 15a8656
increment in index.rst
hodgesmr 2436797
Add test where the opponent defects but we forgive because their over…
hodgesmr 097d501
ran black formatter per repo guidelines
hodgesmr 3a4e569
comment and docstring cleanup
hodgesmr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| """ | ||
| Bayesian Forgiver - A strategy using Bayesian inference for adaptive forgiveness. | ||
|
|
||
| This strategy maintains a Bayesian belief about the opponent's cooperation probability | ||
| using a Beta distribution, and makes forgiveness decisions based on both the estimated | ||
| cooperation rate and the uncertainty in that estimate. | ||
| """ | ||
|
|
||
| from axelrod.action import Action | ||
| from axelrod.player import Player | ||
|
|
||
| C, D = Action.C, Action.D | ||
|
|
||
|
|
||
| class BayesianForgiver(Player): | ||
| """ | ||
| A strategy that uses Bayesian inference to model opponent behavior and | ||
| adaptively adjust forgiveness based on uncertainty. | ||
|
|
||
| The strategy maintains a Beta distribution representing beliefs about the | ||
| opponent's cooperation probability. It uses both the mean (expected cooperation | ||
| rate) and variance (uncertainty) to make decisions: | ||
|
|
||
| - When uncertain about the opponent's nature, it is cautious | ||
| - When certain the opponent is hostile, it punishes consistently | ||
| - When certain the opponent is cooperative, it cooperates consistently | ||
|
|
||
| Algorithm: | ||
| 1. Maintain Beta(alpha, beta) distribution for opponent's cooperation probability | ||
| 2. Start with Beta(1, 1) - neutral/uniform prior | ||
| 3. Update after each round: C → alpha += 1, D → beta += 1 | ||
| 4. Calculate mean = alpha / (alpha + beta) | ||
| 5. Calculate uncertainty (std deviation) | ||
| 6. Adaptive forgiveness: threshold = base_threshold + uncertainty_factor * uncertainty | ||
| 7. Forgive a defection only if the estimated cooperation rate clears this threshold | ||
|
|
||
| Names: | ||
| - Bayesian Forgiver: Original name by Matt Hodges | ||
| """ | ||
|
|
||
| name = "Bayesian Forgiver" | ||
| classifier = { | ||
| "memory_depth": float("inf"), | ||
| "stochastic": False, | ||
| "long_run_time": False, | ||
| "inspects_source": False, | ||
| "manipulates_source": False, | ||
| "manipulates_state": False, | ||
| } | ||
|
|
||
| def __init__( | ||
| self, | ||
| prior_alpha: float = 1.0, | ||
| prior_beta: float = 1.0, | ||
| base_forgiveness_threshold: float = 0.45, | ||
| uncertainty_factor: float = 2.5, | ||
| ) -> None: | ||
| """ | ||
| Initialize the Bayesian Forgiver strategy. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| prior_alpha : float | ||
| Initial alpha parameter for Beta distribution (default: 1.0) | ||
| Represents prior belief in cooperation count + 1 | ||
| Higher values indicate stronger prior belief in cooperation | ||
| prior_beta : float | ||
| Initial beta parameter for Beta distribution (default: 1.0) | ||
| Represents prior belief in defection count + 1 | ||
| Higher values indicate stronger prior belief in defection | ||
| base_forgiveness_threshold : float | ||
| Base threshold for forgiveness decision (default: 0.45) | ||
| If estimated cooperation probability > threshold, forgive defections | ||
| uncertainty_factor : float | ||
| How much uncertainty increases the forgiveness threshold (default: 2.5) | ||
|
|
||
| Note: Default parameters have been optimized through grid search | ||
| to maximize performance against common IPD strategies. | ||
| """ | ||
| super().__init__() | ||
| self.prior_alpha = prior_alpha | ||
| self.prior_beta = prior_beta | ||
| self.base_forgiveness_threshold = base_forgiveness_threshold | ||
| self.uncertainty_factor = uncertainty_factor | ||
|
|
||
| # Initialize Bayesian belief parameters | ||
| self.alpha = prior_alpha | ||
| self.beta = prior_beta | ||
|
|
||
| def reset(self): | ||
| """Reset the strategy to initial state.""" | ||
| super().reset() | ||
| self.alpha = self.prior_alpha | ||
| self.beta = self.prior_beta | ||
|
|
||
| def strategy(self, opponent: Player) -> Action: | ||
| """ | ||
| Determine next action using Bayesian opponent model. | ||
|
|
||
| Returns | ||
| ------- | ||
| Action | ||
| C (cooperate) or D (defect) | ||
| """ | ||
| # First move: Start with cooperation (optimistic prior) | ||
| if not self.history: | ||
| return C | ||
|
|
||
| # Update Bayesian belief based on opponent's last action | ||
| if opponent.history[-1] == C: | ||
| self.alpha += 1.0 | ||
| else: | ||
| self.beta += 1.0 | ||
|
|
||
| # Calculate statistics from Beta distribution | ||
| total = self.alpha + self.beta | ||
| mean_cooperation = self.alpha / total | ||
|
|
||
| # Calculate variance and standard deviation (uncertainty) | ||
| # Var(Beta(α,β)) = αβ / ((α+β)²(α+β+1)) | ||
| variance = (self.alpha * self.beta) / (total * total * (total + 1)) | ||
| uncertainty = variance**0.5 | ||
|
|
||
| # Adaptive forgiveness threshold | ||
| forgiveness_threshold = ( | ||
| self.base_forgiveness_threshold | ||
| + self.uncertainty_factor * uncertainty | ||
| ) | ||
|
|
||
| # Decision logic | ||
| if opponent.history[-1] == C: | ||
| # Opponent cooperated last round - reciprocate cooperation | ||
| return C | ||
| else: | ||
| # Opponent defected last round - decide whether to forgive or punish | ||
| if mean_cooperation >= forgiveness_threshold: | ||
| # Forgive only when the estimated cooperation rate is high enough. | ||
| return C | ||
| else: | ||
| # Opponent appears to be hostile with sufficient confidence | ||
| # Punish the defection | ||
| return D |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you help me understand what is happening with this file @hodgesmr ? Was this done by running https://github.com/Axelrod-Python/Axelrod/blob/dev/axelrod/classifier.py#L91 ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This diff is from the commit: c2619eb
I was following the documentation for adding a new strategy: "To classify the new strategy, run rebuild_classifier_table: python rebuild_classifier_table.py"
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup. Cool.