我如何使拟合在逻辑回归中起作用?

2024-04-18 19:02:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用逻辑回归拟合数据,但我得到了一个值错误

我正在使用sklearn的iris数据集:

# The data is in iris["data"] and target in iris["target"]
# For this section, we will work with a single feature 'petal width'
# which is the last (fourth) feature in iris["data"]
# We will assign class y=1 if the target's value is 2 and 0 otherwise

from sklearn.datasets import load_iris
import numpy as np

iris = load_iris()

# petal width
X = np.array([len(iris["data"]),1]).reshape(-1,1)
# 1 if Iris virginica, else 0
y = []
for x in iris["target"]:
    if x == 2.0:
        y.append(1)
    else:
        y.append(0)
y = np.array(y)

# Import the LogisticRegression class from scikit learn
from sklearn.linear_model import LogisticRegression

# Initialize the LogisticRegression class, use lbfgs solver and random state of 42
log_reg = LogisticRegression(solver='lbfgs', random_state=42)

# Fit the data
log_reg.fit(X, y)

这就是我到达的地方

ValueError: Found input variables with inconsistent numbers of samples: [2, 150]

不确定是我的x还是y设置不正确


Tags: andthe数据infromimportiristarget
1条回答
网友
1楼 · 发布于 2024-04-18 19:02:31

原因是您在此处尝试的X的整形错误:

X = np.array([len(iris["data"]),1]).reshape(-1,1)

结果是

X.shape
# (2,1)

因此样本数量不一致,因为

y.shape
# (150,)

这种重塑是错误的;因为,正如代码中的注释所示,您只需要第四个特性(花瓣宽度),所以应该将其更改为:

X = iris['data'][:,3].reshape(-1,1)

这确实给出了正确的形状:

X.shape
# (150, 1)

您的模型将安装无问题(已测试)

相关问题 更多 >