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

Fix shape mismatch error in CatCMASampler for categorical problems #171

Merged
merged 4 commits into from
Nov 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions package/samplers/catcma/catcma.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,23 +199,36 @@ def sample_relative(
solution_trials = self._get_solution_trials(completed_trials, optimizer.generation)

if len(solution_trials) >= popsize:
solutions: List[Tuple[np.ndarray, float]] = []
# Calculate the number of categorical variables and maximum number of choices
num_categorical_vars = len(categorical_search_space)
max_num_choices = max(
len(space.choices) for space in categorical_search_space.values()
)

# Prepare solutions list
solutions: List[Tuple[Tuple[np.ndarray, np.ndarray], float]] = []

for t in solution_trials[:popsize]:
assert t.value is not None, "completed trials must have a value"
# Convert Optuna's representation to cmaes.CatCma's internal representation.

# Convert numerical parameters
x = trans.transform({k: t.params[k] for k in numerical_search_space.keys()})

# Convert categorial values to one-hot vectors.
# Example:
# choices = ['a', 'b', 'c']
# value = 'b'
# one_hot_vec = [False, True, False]
c = np.asarray(
[
[c == v for c in categorical_search_space[k].choices]
for k, v in t.params.items()
if k in categorical_search_space.keys()
]
)
c = np.zeros((num_categorical_vars, max_num_choices))

for idx, k in enumerate(categorical_search_space.keys()):
choices = categorical_search_space[k].choices
v = t.params.get(k)
if v is not None:
index = choices.index(v)
c[idx, index] = 1

y = t.value if study.direction == StudyDirection.MINIMIZE else -t.value
solutions.append(((x, c), y)) # type: ignore

Expand Down