How SelectKBest chi2 calculates score?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Feature selection is a crucial step in the preprocessing pipeline of machine learning. It helps in reducing the dimensionality of a dataset, which consequently improves the speed and accuracy of models and reduces overfitting. One of the popular methods for feature selection is `SelectKBest`, which is available in Scikit-learn—a well-known Python library for machine learning.
The `SelectKBest` function allows users to select features according to the k highest scores. Among the various scoring functions available, the Chi-Squared () statistics is commonly used for classification tasks where the target variable is categorical. This article provides a detailed explanation of how `SelectKBest` using chi-square () calculates the scores for selecting features.
Understanding Chi-Square () Statistic
The chi-square test is a statistical test used to determine whether there is a significant association between two categorical variables. The statistic measures how expectations compare with actual observed data. The formula for the chi-square statistic is:
where represents the observed frequency and represents the expected frequency of the occurrences.
Calculation Steps
- Create Contingency Table: • For each feature, cross-tabulate the values of the feature against the target variable. This forms a contingency table where each row sums to the frequency of the feature, and each column sums to the frequency of the class labels.
- Calculate Expected Frequencies: • Calculate the expected frequency for each cell in the contingency table using the formula: • Here, is the expected frequency for the entry of the row and the column.
- Compute Chi-Square Statistic: • Use the observed and expected frequencies to calculate the statistic as shown in the formula above.
- Determine p-Value: • While `SelectKBest` primarily uses the statistic for ranking features, the p-value could also be calculated for statistical significance assessment. It determines the probability of observing the data given that the null hypothesis is true (i.e., no association).
- Ranking Features: • The
$ \chi^2$ statistics calculated for each feature are used to rank them. `SelectKBest` selects the top k features with the highest $\chi^2 $scores for use in the learning algorithm.
Example
Consider a toy dataset with two features and a binary target variable.
| Instance | Feature 1 | Feature 2 | Target |
| 1 | High | Yes | 1 |
| 2 | Medium | No | 0 |
| 3 | Medium | Yes | 1 |
| 4 | Low | Yes | 0 |
| 5 | Low | No | 1 |
Step-by-Step Calculation
• Feature 1: • Contingency (example):
| Class 1 | Class 0 | Total | |
| High | 1 | 0 | 1 |
| Medium | 1 | 1 | 2 |
| Low | 1 | 1 | 2 |
| Total | 3 | 2 | 5 |
• Expected Frequency Calculation: • For example, the expected frequency for High-Class 1 is:
• Calculate for Feature 1:
• Feature 2: • Similar calculations performed for contingency table and statistic.
Conclusion
The `SelectKBest` with chi-square () is highly valuable for feature selection in machine learning. By statistically quantifying the dependency between each feature and the target variable, it enables data scientists to efficiently reduce the number of input variables to the model. Despite its effectiveness, it is important to use this method primarily for categorical data, as it requires the features and target to be non-negative and discrete for meaningful calculations.
| Step | Description |
| Create Contingency Table | Cross-tabulate feature vs. target |
| Calculate Expected | Use marginal sums to compute expected frequencies |
| Compute | Measure deviation of observed from expected values |
| Determine p-value | Assess statistical significance |
| Rank Features | Select features with the highest scores |
In summary, the SelectKBest method with chi-square is a fundamental tool that empowers practitioners to build more efficient and interpretable machine learning models.
Related reading
- How should BatchNorm layer be used in caffe?
- How should I handle input data with nan values in TensorFlow?
- How should I use torch.compile properly?
- How should I vectorize the following list of lists with scikit learn?
- How should the learning rate change as the batch size change?
- How TensorArray and while_loop work together in tensorflow?
- How tf.gradients work in TensorFlow
- How tf.gradients work in TensorFlow
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.