gale.ai.learning module

This file contains two lightweight models an agent can use to build up knowledge about another agent (typically the player) from observed behavior, instead of having its reactions hand-scripted: a NaiveBayesClassifier to predict a discrete label (e.g. “aggressive” vs “defensive” play style) from a set of features, and an NGramPredictor to predict the next action in a sequence from how often it has followed the same recent actions before (e.g. anticipating whether the player is about to dodge left, dodge right, or attack).

Author: Alejandro Mujica (aledrums@gmail.com)

class gale.ai.learning.NaiveBayesClassifier[source]

Bases: object

A naive Bayes classifier over discrete features: learns P(label) and P(feature_value | label) from observed examples, then predicts the label maximizing their product (assuming features are independent given the label, the “naive” assumption) for a new set of features.

Usage example:

model = NaiveBayesClassifier() model.observe(“aggressive”, {“approach_speed”: “fast”, “range”: “melee”}) model.observe(“defensive”, {“approach_speed”: “slow”, “range”: “ranged”}) model.predict({“approach_speed”: “fast”, “range”: “melee”}) # “aggressive”

observe(label, features)[source]

Record one labeled example.

Parameters:
  • label (Hashable) – The label this example belongs to.

  • features (Dict[str, Any]) – Feature name -> discrete value pairs observed alongside label.

Return type:

None

predict(features)[source]
Parameters:

features (Dict[str, Any]) – Feature name -> discrete value pairs to classify.

Returns:

The label with the highest estimated posterior probability given features, or None if no example has been observed yet.

Return type:

Hashable | None

class gale.ai.learning.NGramPredictor(n=3)[source]

Bases: object

Predicts the next action in a sequence from how often it has followed the same n-1 most recent actions before, learned online from observe(). Useful to anticipate a player’s next move (e.g. in a fighting game or a stealth encounter) well enough to react to a pattern without the player realizing they’ve fallen into one.

Usage example:

predictor = NGramPredictor(n=3) for action in [“dodge_left”, “attack”, “dodge_left”, “attack”]:

predictor.observe(action)

predictor.predict_next() # “dodge_left”, the most common

# follow-up seen after [“dodge_left”, “attack”]

Parameters:

n (int)

observe(action)[source]

Record that action happened right after the current history, then append it to the history for the next call.

Parameters:

action (Hashable) – The action observed.

Return type:

None

predict_next()[source]
Returns:

The action most often observed right after the current history, or None if this exact context has never been seen before.

Return type:

Hashable | None

reset_history()[source]

Clear the current context (e.g. at the start of a new encounter) without discarding what has been learned.

Return type:

None