StringSimilarityEncoder#
- class feature_engine.encoding.StringSimilarityEncoder(top_categories=None, keywords=None, missing_values='impute', variables=None, ignore_format=False)[source]#
The StringSimilarityEncoder() replaces categorical variables with a set of float variables that capture the similarity between the category names. The new variables have values between 0 and 1, where 0 indicates no similarity and 1 is an exact match between the names of the categories.
The similarity measure is a float in the range [0, 1]. It is defined as 2 * M / T, where T is the total number of elements in both categories being compared, and M is the number of matches. Note that this is 1 if the sequences are identical, and 0 if they have nothing in common.
For example, the similarity between the categories “dog” and “dig” is 0.66. T is the total number of elements in both categories, that is 6. There are 2 matches between the words, the letters d and g, so: 2 * M / T = 2 * 2 / 6 = 0.66.
This encoding is similar to one-hot encoding, in the sense that each category is encoded as a new variable. But the values, instead of 1 or 0, are the similarity between the observation’s category and the dummy variable.
For example, if a variable has 3 categories, dog, dig and cat, StringSimilarityEncoder() will create 3 new variables, var_dog, var_dig and var_cat and the values would be for the observation dog: 1, 0.66 , 0. For the observation dig they would be 0.66, 1, 0. And for cat, they would be 0, 0, 1.
The encoder has the option to generate similarity variables only for the most popular categories, that is, the categories present in most observations. This behaviour can be specified with the parameter
top_categories
.Missing values
StringSimilarityEncoder() will rreplace missing data with an empty string and then return the similarity to the remaining variables by default. Alternatively, it can be set to return an error if the variable has missing values, or to ignore them.
Unseen categories
StringSimilarityEncoder() handles unseen categories out-of-the-box by assigning a similarity measure to the other categories that were seen during
fit()
.Categorical variables
The encoder will encode only categorical variables by default (type ‘object’ or ‘categorical’). You can pass a list of variables to encode. Alternatively, the encoder will find and encode all categorical variables.
Numerical variables
With
ignore_format=True
you have the option to encode numerical variables as well. Encoding numerical variables with similarity measures make sense for example for variables like barcodes. In this case, you can either enter the list of variables to encode (recommended), or the transformer will automatically select all variables.More details in the User Guide.
- Parameters
- top_categories: int, default=None
If None, dummy variables will be created for each unique category of the variable. Alternatively, we can indicate in the number of most frequent categories to encode. In this case, similarity variables will be created only for those popular categories.
- missing_values: str, default=’impute’
Indicates if missing values should be ignored, raised or imputed. If ‘raise’ the transformer will return an error if the datasets to
fit
ortransform
contain missing values. If ‘ignore’, missing data will be ignored when learning parameters or performing the transformation. If ‘impute’, the transformer will replace missing values with an empty string, ‘’, and then return the similarity measures.- keywords: dict, default=None
Dictionary with a set of keywords to be used to create the similarity variables. The format should be: dict(feature: [keyword1, keyword2, …]). The encoder will use these keywords to create the similarity variables. The dictionary can be defined for all the features to encode, or only for a subset of them. In this case, for the features not specified in the dictionary, the encoder will identify the categories from the data.
- variables: list, default=None
The list of categorical variables that will be encoded. If None, the encoder will find and transform all variables of type object or categorical by default. You can also make the transformer accept numerical variables, see the parameter
ignore_format
.- ignore_format: bool, default=False
This transformer operates only on variables of type object or categorical. To override this behaviour and allow the transformer to transform numerical variables as well, set to
True
.If
ignore_format
isFalse
, the encoder will automatically select variables of type object or categorical, or check that the variables entered by the user are of type object or categorical. IfTrue
, the encoder will select all variables or accept all variables entered by the user, including those cast as numeric.In short, set to
True
when you want to encode numerical variables.
- Attributes
- encoder_dict_:
Dictionary with the categories for which dummy variables will be created.
- variables_:
The group of variables that will be transformed.
- feature_names_in_:
List with the names of features seen during
fit
.- n_features_in_:
The number of features in the train set used in fit.
See also
feature_engine.encoding.OneHotEncoder
dirty_cat.SimilarityEncoder
Notes
This encoder will encode unseen categories by measuring string similarity between seen and unseen categories.
No text preprocessing is applied before calculating the similarity.
The original categorical variables are removed from the returned dataset after the transformation. In their place, the binary variables are returned.
References
- 1
Cerda P, Varoquaux G, Kégl B. “Similarity encoding for learning with dirty categorical variables”. Machine Learning, Springer Verlag, 2018.
- 2
Cerda P, Varoquaux G. “Encoding high-cardinality string categorical variables”. IEEE Transactions on Knowledge & Data Engineering, 2020.
Examples
>>> import pandas as pd >>> from feature_engine.encoding import StringSimilarityEncoder >>> X = pd.DataFrame(dict(x1 = [1,2,3,4], x2 = ["dog", "dig", "dagger", "hi"])) >>> sse = StringSimilarityEncoder() >>> sse.fit(X) >>> sse.transform(X) x1 x2_dog x2_dig x2_dagger x2_hi 0 1 1.000000 0.666667 0.444444 0.0 1 2 0.666667 1.000000 0.444444 0.4 2 3 0.444444 0.444444 1.000000 0.0 3 4 0.000000 0.400000 0.000000 1.0
Methods
fit:
Learn the unique categories per variable.
fit_transform:
Fit to data, then transform it.
get_feature_names_out:
Get output feature names for transformation.
get_params:
Get parameters for this estimator.
set_params:
Set the parameters of this estimator.
transform:
Replace the categorical variables by the distance variables.
- fit(X, y=None)[source]#
Learns the unique categories per variable. If top_categories is indicated, it will learn the most popular categories. Alternatively, it learns all unique categories per variable.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The training input samples. Can be the entire dataframe, not just the variables to encode.
- y: pandas series, default=None
Target. It is not needed in this encoded. You can pass y or None.
- fit_transform(X, y=None, **fit_params)[source]#
Fit to data, then transform it.
Fits transformer to
X
andy
with optional parametersfit_params
and returns a transformed version ofX
.- Parameters
- Xarray-like of shape (n_samples, n_features)
Input samples.
- yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
- **fit_paramsdict
Additional fit parameters.
- Returns
- X_newndarray array of shape (n_samples, n_features_new)
Transformed array.
- get_feature_names_out(input_features=None)[source]#
Get output feature names for transformation. In other words, returns the variable names of transformed dataframe.
- Parameters
- input_featuresarray or list, default=None
This parameter exits only for compatibility with the Scikit-learn pipeline.
If
None
, thenfeature_names_in_
is used as feature names in.If an array or list, then
input_features
must matchfeature_names_in_
.
- Returns
- feature_names_out: list
Transformed feature names.
- get_params(deep=True)[source]#
Get parameters for this estimator.
- Parameters
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
- paramsdict
Parameter names mapped to their values.
- set_params(**params)[source]#
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
- **paramsdict
Estimator parameters.
- Returns
- selfestimator instance
Estimator instance.
- transform(X)[source]#
Replaces the categorical variables with the similarity variables.
- Parameters
- X: pandas dataframe of shape = [n_samples, n_features]
The data to transform.
- Returns
- X_new: pandas dataframe.
The transformed dataframe. The shape of the dataframe will be different from the original as it includes the similarity variables in place of the original categorical ones.
- rtype
DataFrame
..