TargetEncoder<T>
Models & Types · AiDotNet.Preprocessing.Encoders
Encodes categorical features using target mean encoding.
Inheritance: TransformerBase<T, Matrix<T>, Matrix<T>> → TargetEncoder<T>
For Beginners
Instead of one-hot encoding (many columns), target encoding creates a single column per feature containing the average target value for each category:
- Category “A” with average target 0.8 becomes 0.8
- Category “B” with average target 0.3 becomes 0.3
This is especially useful for high-cardinality features where one-hot would create too many columns.
How It Works
TargetEncoder replaces each category with the mean of the target variable for that category. This creates a continuous feature that captures the relationship between the category and target.
To prevent overfitting, especially with rare categories, smoothing is applied: encoding = (count * category_mean + smoothing * global_mean) / (count + smoothing)
Constructors
| Constructor | Summary |
|---|---|
TargetEncoder(double smoothing, double minSamplesLeaf, TargetEncoderHandleUnknown handleUnknown, int[] columnIndices) |
Creates a new instance of TargetEncoder. |
Properties
| Property | Summary |
|---|---|
Dictionary<int, CategoryValueMap<T>> EncodingMaps { get; } |
Gets the encoding maps for each column. |
TargetEncoderHandleUnknown HandleUnknown { get; } |
Gets how unknown categories are handled during transform. |
bool SupportsInverseTransform { get; } |
Gets whether this transformer supports inverse transformation. |
double Smoothing { get; } |
Gets the smoothing parameter used during encoding. |
Methods
| Method | Summary |
|---|---|
Matrix<T> FitTransform(Matrix<T> data, Vector<T> target) |
Fits the encoder and transforms the data in one step. |
string[] GetFeatureNamesOut(string[] inputFeatureNames) |
Gets the output feature names after transformation. |
void Fit(Matrix<T> data, Vector<T> target) |
Fits the encoder by learning the target means for each category. |