使用MXM库MMPC算法进行Max-Min Parents and Children特征选择报错求助
'x' must be numeric Error in MMPC (MXM Library) Let's break down why you're hitting this error and walk through the fixes step by step:
Why the Error Happens
Your target variable Cardio1M is a 6-level factor (categorical), but you're using test='testIndFisher'. Here's the core issue:
- The Fisher exact test (
testIndFisher) is designed only for 2x2 contingency tables (binary target + binary feature). It doesn't support multi-class targets like your 6-level factor. - To make matters worse, the internal implementation of this test in MXM incorrectly tries to calculate a correlation (
cor()) between your factor target and features—but thecor()function requires numeric inputs, hence the'x' must be numericerror.
Step-by-Step Solutions
1. Use the Right Independence Test for Mixed Variable Types
Since your dataset has both categorical (factor) and numeric features, and your target is multi-class categorical, use test='testIndGeneral'. This test automatically selects the appropriate method based on variable types:
- For categorical features: Uses chi-squared test to check independence with the target
- For numeric features: Uses ANOVA to check if feature means differ across target classes
Update your code to:
mxres <- MMPC(data$Cardio1M, data[,-72], max_k = 3, threshold = 0.05, test = 'testIndGeneral')
2. Verify Target Variable Type
Double-check that Cardio1M is properly encoded as a factor. If it's stored as an integer or character, convert it first:
# Check current class of the target variable class(data$Cardio1M) # Convert to factor if needed data$Cardio1M <- as.factor(data$Cardio1M)
3. Alternative: Dummy Encode Categorical Features (If Needed)
If testIndGeneral still gives you trouble, you can convert all categorical features to numeric dummy variables. This lets you use ANOVA (test='testIndANOVA') for all features (since dummies are 0/1 numeric values):
# Create dummy variables for all features (remove intercept to avoid redundancy) features_dummies <- model.matrix(~ . - 1, data = data[,-72]) # Run MMPC with ANOVA test mxres <- MMPC(data$Cardio1M, features_dummies, max_k = 3, threshold = 0.05, test = 'testIndANOVA')
内容的提问来源于stack exchange,提问作者Aymen Trabelsi

