"ValueError: y should be a 1d array, got an array of shape (3, 4) instead." While using fit() from sklearn
"ValueError: y should be a 1d array, got an array of shape (3, 4) instead." While using fit() from sklearn
我输入:
import numpy as np
from sklearn.linear_model import LogisticRegression
label_list = np.array([1,2,3])
label_list = label_list.reshape(-1,1)
feature_matrix = np.array([[0,0,1,1],[0,1,0,1],[1,0,0,1]])
model = LogisticRegression()
model.fit(label_list,feature_matrix)
然后我的控制台输出:
ValueError: y should be a 1d array, got an array of shape (3, 4) instead.
我该如何解决?我是初学者。请说清楚。
根据示例代码,我了解到 label_list
是“目标向量”(y
),feature_matrix
是 X
矩阵。
所以,正确的用法应该是:
model.fit(feature_matrix, label_list)
此外,您无法重塑 label_list
:
label_list = label_list.reshape(-1,1)
因为 model.fit()
需要一个形状为 (n_samples,)
的向量,而你给出的向量形状为 (n_samples, 1)
.
总而言之,您的代码应如下所示:
import numpy as np
from sklearn.linear_model import LogisticRegression
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()
model.fit(feature_matrix, label_list)
我输入:
import numpy as np
from sklearn.linear_model import LogisticRegression
label_list = np.array([1,2,3])
label_list = label_list.reshape(-1,1)
feature_matrix = np.array([[0,0,1,1],[0,1,0,1],[1,0,0,1]])
model = LogisticRegression()
model.fit(label_list,feature_matrix)
然后我的控制台输出:
ValueError: y should be a 1d array, got an array of shape (3, 4) instead.
我该如何解决?我是初学者。请说清楚。
根据示例代码,我了解到 label_list
是“目标向量”(y
),feature_matrix
是 X
矩阵。
所以,正确的用法应该是:
model.fit(feature_matrix, label_list)
此外,您无法重塑 label_list
:
label_list = label_list.reshape(-1,1)
因为 model.fit()
需要一个形状为 (n_samples,)
的向量,而你给出的向量形状为 (n_samples, 1)
.
总而言之,您的代码应如下所示:
import numpy as np
from sklearn.linear_model import LogisticRegression
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()
model.fit(feature_matrix, label_list)