报错TypeError:此数据类型不允许归约操作'argmax',求代码问题排查
Hey there, let's break down this error and fix it step by step! That argmax error almost always boils down to non-numeric data types sneaking into your model inputs—either your target variable or your features aren't in a format scikit-learn can work with for classification tasks like Logistic Regression.
Why This Happens
The argmax operation is used internally by scikit-learn to predict class labels (e.g., picking the highest probability class). It only works on numeric data types (int, float, etc.). If your target labels (y_train_data) are strings (like "positive"/"negative") or your features have non-numeric columns, this error pops up.
Step-by-Step Troubleshooting & Fixes
1. Check Your Target Variable (y_train_data)
First, verify the data type of your labels:
print(y_train_data.dtype)
If the output is object (meaning it's storing strings), you need to convert these to numeric labels using LabelEncoder:
from sklearn.preprocessing import LabelEncoder # Convert string labels to numeric le = LabelEncoder() y_train_data = le.fit_transform(y_train_data)
This turns labels like "yes"/"no" into 1/0, which works with argmax.
2. Check Your Feature Data (x_train_data)
Next, make sure all your features are numeric. Run this to see data types for each column:
print(x_train_data.dtypes)
If any columns show object, you'll need to encode them:
- For categorical features with no order (like
"red"/"blue"/"green"), use one-hot encoding:x_train_data = pd.get_dummies(x_train_data) - For ordered categorical features (like
"low"/"medium"/"high"), useLabelEncoderinstead.
3. Verify Your Incomplete DataFrame Code
Your code cuts off at results_table = pd.DataFr...—if you're later using this DataFrame to store model results, make sure any columns used in argmax-related operations are numeric. Double-check that you're not accidentally storing strings or non-numeric values here.
Example Fixed Code
Here's how your function might look with these fixes applied:
import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import KFold, cross_val_score from sklearn.metrics import confusion_matrix, precision_recall_curve, auc, roc_auc_score, roc_curve, recall_score, classification_report from sklearn.preprocessing import LabelEncoder def printing_Kfold_scores(x_train_data, y_train_data): # Fix 1: Convert target labels to numeric if needed if y_train_data.dtype == 'object': le = LabelEncoder() y_train_data = le.fit_transform(y_train_data) # Fix 2: Encode non-numeric features x_train_data = pd.get_dummies(x_train_data) fold = KFold(len(y_train_data), 5, shuffle=False) c_param_range = [0.01, 0.1, 1, 10, 100] results_table = pd.DataFrame(columns=['C_parameter', 'Mean recall score']) results_table['C_parameter'] = c_param_range # Cross-validation loop for i, c_param in enumerate(c_param_range): print(f'C parameter: {c_param}') recall_accs = [] for iteration, indices in enumerate(fold, start=1): # Initialize model with current C parameter lr = LogisticRegression(C=c_param, penalty='l1') lr.fit(x_train_data.iloc[indices[0]], y_train_data.iloc[indices[0]]) # Predict and calculate recall y_pred = lr.predict(x_train_data.iloc[indices[1]]) recall_acc = recall_score(y_train_data.iloc[indices[1]], y_pred) recall_accs.append(recall_acc) print(f'Iteration {iteration}, recall score: {recall_acc}') # Store mean recall for this C parameter results_table.loc[i, 'Mean recall score'] = np.mean(recall_accs) # Optional: Print best C parameter best_c = results_table.loc[results_table['Mean recall score'].idxmax(), 'C_parameter'] print(f'\nBest C parameter: {best_c}') return results_table
If the Error Persists
If you still see the error, share the output of x_train_data.dtypes and y_train_data.dtype—that will help pinpoint exactly which column is causing the issue.
内容的提问来源于stack exchange,提问作者ROSA LILI

