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

Use vectorization for categorical distance #5147

36 changes: 20 additions & 16 deletions optuna/samplers/_tpe/parzen_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,29 +185,33 @@ def _calculate_categorical_distributions(
search_space: CategoricalDistribution,
parameters: _ParzenEstimatorParameters,
) -> _BatchedDistributions:
consider_prior = parameters.consider_prior or len(observations) == 0
choices = search_space.choices
n_choices = len(choices)
n_samples = observations.size + (parameters.consider_prior or observations.size == 0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the name n_samples might not be appropriate, because this includes prior. Maybe n_mixture may be better?


assert parameters.prior_weight is not None
weights = np.full(
shape=(len(observations) + consider_prior, len(search_space.choices)),
fill_value=parameters.prior_weight / (len(observations) + consider_prior),
shape=(n_samples, n_choices),
fill_value=parameters.prior_weight / n_samples,
)

if param_name in parameters.categorical_distance_func:
observed_indices = observations.astype(int)
if observed_indices.size == 0:
# Do nothing.
pass
elif param_name in parameters.categorical_distance_func:
# TODO(nabenabe0928): Think about how to handle combinatorial explosion.
# The time complexity is O(n_choices * used_indices.size), so n_choices cannot be huge.
used_indices, rev_indices = np.unique(observed_indices, return_inverse=True)
dist_func = parameters.categorical_distance_func[param_name]
for i, observation in enumerate(observations.astype(int)):
dists = [
dist_func(search_space.choices[observation], search_space.choices[j])
for j in range(len(search_space.choices))
]
exponent = -(
(np.array(dists) / max(dists)) ** 2
* np.log((len(observations) + consider_prior) / parameters.prior_weight)
* (np.log(len(search_space.choices)) / np.log(6))
)
weights[i] = np.exp(exponent)
dists = np.array([[dist_func(choices[i], c) for c in choices] for i in used_indices])
max_dists = np.max(dists, axis=1)
coef = np.log(n_samples / parameters.prior_weight) * np.log(n_choices) / np.log(6)
categorical_weights = np.exp(-((dists / max_dists[:, np.newaxis]) ** 2) * coef)
weights[: observed_indices.size] = categorical_weights[rev_indices]
else:
weights[np.arange(len(observations)), observations.astype(int)] += 1
weights[np.arange(observed_indices.size), observed_indices] += 1

weights /= weights.sum(axis=1, keepdims=True)
return _BatchedCategoricalDistributions(weights)

Expand Down