|
| 1 | +from typing import Any, Dict, Optional, Tuple, Union |
| 2 | + |
| 3 | +from ConfigSpace.configuration_space import ConfigurationSpace |
| 4 | +from ConfigSpace.hyperparameters import ( |
| 5 | + UniformFloatHyperparameter, |
| 6 | + UniformIntegerHyperparameter |
| 7 | +) |
| 8 | + |
| 9 | +import numpy as np |
| 10 | + |
| 11 | +import torch |
| 12 | +from torch import nn |
| 13 | + |
| 14 | +from autoPyTorch.pipeline.components.setup.network_embedding.base_network_embedding import NetworkEmbeddingComponent |
| 15 | + |
| 16 | + |
| 17 | +class _LearnedEntityEmbedding(nn.Module): |
| 18 | + """ Learned entity embedding module for categorical features""" |
| 19 | + |
| 20 | + def __init__(self, config: Dict[str, Any], num_input_features: np.ndarray, num_numerical_features: int): |
| 21 | + """ |
| 22 | + Arguments: |
| 23 | + config (Dict[str, Any]): The configuration sampled by the hyperparameter optimizer |
| 24 | + num_input_features (np.ndarray): column wise information of number of output columns after transformation |
| 25 | + for each categorical column and 0 for numerical columns |
| 26 | + num_numerical_features (int): number of numerical features in X |
| 27 | + """ |
| 28 | + super().__init__() |
| 29 | + self.config = config |
| 30 | + |
| 31 | + self.num_numerical = num_numerical_features |
| 32 | + # list of number of categories of categorical data |
| 33 | + # or 0 for numerical data |
| 34 | + self.num_input_features = num_input_features |
| 35 | + categorical_features = self.num_input_features > 0 |
| 36 | + |
| 37 | + self.num_categorical_features = self.num_input_features[categorical_features] |
| 38 | + |
| 39 | + self.embed_features = [num_in >= config["min_unique_values_for_embedding"] for num_in in |
| 40 | + self.num_input_features] |
| 41 | + self.num_output_dimensions = [0] * num_numerical_features |
| 42 | + self.num_output_dimensions.extend([config["dimension_reduction_" + str(i)] * num_in for i, num_in in |
| 43 | + enumerate(self.num_categorical_features)]) |
| 44 | + self.num_output_dimensions = [int(np.clip(num_out, 1, num_in - 1)) for num_out, num_in in |
| 45 | + zip(self.num_output_dimensions, self.num_input_features)] |
| 46 | + self.num_output_dimensions = [num_out if embed else num_in for num_out, embed, num_in in |
| 47 | + zip(self.num_output_dimensions, self.embed_features, |
| 48 | + self.num_input_features)] |
| 49 | + self.num_out_feats = self.num_numerical + sum(self.num_output_dimensions) |
| 50 | + |
| 51 | + self.ee_layers = self._create_ee_layers() |
| 52 | + |
| 53 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 54 | + # pass the columns of each categorical feature through entity embedding layer |
| 55 | + # before passing it through the model |
| 56 | + concat_seq = [] |
| 57 | + last_concat = 0 |
| 58 | + x_pointer = 0 |
| 59 | + layer_pointer = 0 |
| 60 | + for num_in, embed in zip(self.num_input_features, self.embed_features): |
| 61 | + if not embed: |
| 62 | + x_pointer += 1 |
| 63 | + continue |
| 64 | + if x_pointer > last_concat: |
| 65 | + concat_seq.append(x[:, last_concat: x_pointer]) |
| 66 | + categorical_feature_slice = x[:, x_pointer: x_pointer + num_in] |
| 67 | + concat_seq.append(self.ee_layers[layer_pointer](categorical_feature_slice)) |
| 68 | + layer_pointer += 1 |
| 69 | + x_pointer += num_in |
| 70 | + last_concat = x_pointer |
| 71 | + |
| 72 | + concat_seq.append(x[:, last_concat:]) |
| 73 | + return torch.cat(concat_seq, dim=1) |
| 74 | + |
| 75 | + def _create_ee_layers(self) -> nn.ModuleList: |
| 76 | + # entity embeding layers are Linear Layers |
| 77 | + layers = nn.ModuleList() |
| 78 | + for i, (num_in, embed, num_out) in enumerate(zip(self.num_input_features, self.embed_features, |
| 79 | + self.num_output_dimensions)): |
| 80 | + if not embed: |
| 81 | + continue |
| 82 | + layers.append(nn.Linear(num_in, num_out)) |
| 83 | + return layers |
| 84 | + |
| 85 | + |
| 86 | +class LearnedEntityEmbedding(NetworkEmbeddingComponent): |
| 87 | + """ |
| 88 | + Class to learn an embedding for categorical hyperparameters. |
| 89 | + """ |
| 90 | + |
| 91 | + def __init__(self, random_state: Optional[Union[np.random.RandomState, int]] = None, **kwargs: Any): |
| 92 | + super().__init__(random_state=random_state) |
| 93 | + self.config = kwargs |
| 94 | + |
| 95 | + def build_embedding(self, num_input_features: np.ndarray, num_numerical_features: int) -> nn.Module: |
| 96 | + return _LearnedEntityEmbedding(config=self.config, |
| 97 | + num_input_features=num_input_features, |
| 98 | + num_numerical_features=num_numerical_features) |
| 99 | + |
| 100 | + @staticmethod |
| 101 | + def get_hyperparameter_search_space( |
| 102 | + dataset_properties: Optional[Dict[str, str]] = None, |
| 103 | + min_unique_values_for_embedding: Tuple[Tuple, int, bool] = ((3, 7), 5, True), |
| 104 | + dimension_reduction: Tuple[Tuple, float] = ((0, 1), 0.5), |
| 105 | + ) -> ConfigurationSpace: |
| 106 | + cs = ConfigurationSpace() |
| 107 | + min_hp = UniformIntegerHyperparameter("min_unique_values_for_embedding", |
| 108 | + lower=min_unique_values_for_embedding[0][0], |
| 109 | + upper=min_unique_values_for_embedding[0][1], |
| 110 | + default_value=min_unique_values_for_embedding[1], |
| 111 | + log=min_unique_values_for_embedding[2] |
| 112 | + ) |
| 113 | + cs.add_hyperparameter(min_hp) |
| 114 | + if dataset_properties is not None: |
| 115 | + for i in range(len(dataset_properties['categorical_columns'])): |
| 116 | + ee_dimensions_hp = UniformFloatHyperparameter("dimension_reduction_" + str(i), |
| 117 | + lower=dimension_reduction[0][0], |
| 118 | + upper=dimension_reduction[0][1], |
| 119 | + default_value=dimension_reduction[1] |
| 120 | + ) |
| 121 | + cs.add_hyperparameter(ee_dimensions_hp) |
| 122 | + return cs |
| 123 | + |
| 124 | + @staticmethod |
| 125 | + def get_properties(dataset_properties: Optional[Dict[str, Any]] = None) -> Dict[str, Union[str, bool]]: |
| 126 | + return { |
| 127 | + 'shortname': 'embedding', |
| 128 | + 'name': 'LearnedEntityEmbedding', |
| 129 | + 'handles_tabular': True, |
| 130 | + 'handles_image': False, |
| 131 | + 'handles_time_series': False, |
| 132 | + } |
0 commit comments