You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sklearn的fit()方法时遇ValueError报错:y应为一维数组却得到形状(3,4)数组的解决方法

Fixing the ValueError in LogisticRegression.fit()

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:08:10