使用sklearn的fit()方法时遇ValueError报错:y应为一维数组却得到形状(3,4)数组的解决方法
Hey there! Let's sort out this error you're hitting—it's a common mix-up for beginners, so no worries. Here's what's going wrong and how to fix it:
1. You mixed up the order of arguments in fit()
The fit() method for scikit-learn's LogisticRegression follows a strict order: first the feature matrix (X), then the target labels (y).
In your code, you passed label_list (your labels) as the first argument and feature_matrix (your features) as the second. That means sklearn was trying to treat your 3x4 feature matrix as the target y—which explains the error saying y has shape (3,4) instead of a 1D array.
2. Your label array is 2D (unnecessary for classification)
You reshaped label_list to a 2D array with reshape(-1,1). While sklearn can sometimes tolerate this, classification targets work best as 1D arrays to avoid confusion.
Corrected Code
Here's the fixed version of your code that should work perfectly:
import numpy as np from sklearn.linear_model import LogisticRegression # Keep labels as a 1D array (no need to reshape) label_list = np.array([1,2,3]) feature_matrix = np.array([[0,0,1,1],[0,1,0,1],[1,0,0,1]]) model = LogisticRegression() # Pass features first, labels second model.fit(feature_matrix, label_list)
If you need to keep labels as 2D
If for some reason you have to keep label_list as a 2D array, you can flatten it to 1D when passing to fit() using ravel():
label_list = np.array([1,2,3]).reshape(-1,1) model.fit(feature_matrix, label_list.ravel())
内容的提问来源于stack exchange,提问作者Chawit Sa-artying

