使用sklearn precision_score报TypeError: len() of unsized object求助
TypeError: len() of unsized object with sklearn.metrics.precision_score Let’s break down why you’re hitting this error even when your loaded arrays have the same shape as the working initialized ones, and how to fix it step by step.
Common Causes & Solutions
1. Check Data Types of Loaded Arrays
The most likely culprit is that your loaded y_true and y_pred arrays have an object dtype instead of a numeric type (like float64 or int32). This happens if np.loadtxt encounters non-numeric values (e.g., stray strings, malformed lines) in your .txt files, which makes numpy store the data as objects instead of proper numbers—sklearn can’t process object-type arrays for metrics calculations.
To verify this:
print("y_true dtype:", y_true.dtype) print("y_pred dtype:", y_pred.dtype)
If the output shows object, fix it by explicitly specifying a numeric dtype when loading:
# Force numeric type loading y_true = np.loadtxt('y_true.txt', delimiter=',', dtype=np.float64) y_pred = np.loadtxt('y_pre.txt', delimiter=',', dtype=np.float64)
Or use pandas for more robust parsing (it handles messy file formats better):
import pandas as pd y_true = pd.read_csv('y_true.txt', header=None).values.astype(np.float64) y_pred = pd.read_csv('y_pre.txt', header=None).values.astype(np.float64)
2. Check for Missing/Invalid Values
Another possibility is your loaded arrays contain NaN or inf values, which sklearn can’t process properly and may trigger the len() error.
Check for these issues with:
print("y_true has NaNs:", np.isnan(y_true).any()) print("y_pred has NaNs:", np.isnan(y_pred).any()) print("y_true has infs:", np.isinf(y_true).any()) print("y_pred has infs:", np.isinf(y_pred).any())
If you find invalid values, clean them up (e.g., replace NaN with 0):
# Replace NaNs/infs with 0 y_true = np.nan_to_num(y_true) y_pred = np.nan_to_num(y_pred)
3. Convert One-Hot Arrays to Class Labels
If your data is in one-hot format (which your (392,45) shape suggests), you can convert it to 1D class labels—the most common input format for sklearn metrics—using argmax. This bypasses any edge cases with 2D array handling in older sklearn versions:
y_true_labels = np.argmax(y_true, axis=1) y_pred_labels = np.argmax(y_pred, axis=1) print(precision_score(y_true_labels, y_pred_labels, average='micro'))
4. Update scikit-learn
If none of the above work, you might be using an outdated version of scikit-learn that has bugs handling 2D one-hot arrays. Update it with:
pip install --upgrade scikit-learn
Quick Verification Step
After fixing the data, double-check the arrays are valid before calling precision_score:
# Ensure arrays are 2D numeric arrays assert y_true.ndim == 2 and np.issubdtype(y_true.dtype, np.number) assert y_pred.ndim == 2 and np.issubdtype(y_pred.dtype, np.number)
内容的提问来源于stack exchange,提问作者hding

