【问题标题】:python scikit learn logistic regression errorpython scikit学习逻辑回归错误
【发布时间】:2018-08-17 23:56:06
【问题描述】:

我正在尝试根据以下数据绘制逻辑回归图

X = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
y = np.array([0,0,0,0,1,0,1,0,1,1,1,1])

但是当我尝试时:

import numpy as np
import matplotlib.pyplot as plt

from sklearn import linear_model

X = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
y = np.array([0,0,0,0,1,0,1,0,1,1,1,1])

clf = linear_model.LogisticRegression(C=1e5)
clf.fit(X, y)

我收到以下错误:

ValueError: Found input variables with inconsistent numbers of samples: [1, 12]

我有点困惑,为什么它认为 X 或 y 只有一个样本。

【问题讨论】:

    标签: python scikit-learn logistic-regression


    【解决方案1】:

    现代版本的 sklearn 期望二维数组为 X,因此请尝试按照错误消息中的建议对其进行重塑:

    In [7]: clf.fit(X.reshape(-1,1), y)
    Out[7]:
    LogisticRegression(C=100000.0, class_weight=None, dual=False,
              fit_intercept=True, intercept_scaling=1, max_iter=100,
              multi_class='ovr', n_jobs=1, penalty='l2', random_state=None,
              solver='liblinear', tol=0.0001, verbose=0, warm_start=False)
    

    顺便说一句,sklearn 0.19.1 给了我一个明确的错误信息:

    In [10]: sklearn.__version__
    Out[10]: '0.19.1'
    
    In [11]: clf.fit(X, y)
    ...
    skipped
    ...
    ValueError: Expected 2D array, got 1D array instead:
    array=[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11.].
    Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
    

    更新:完整代码:

    In [41]: %paste
    import numpy as np
    import matplotlib.pyplot as plt
    
    from sklearn import linear_model
    import sklearn
    
    X = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
    y = np.array([0,0,0,0,1,0,1,0,1,1,1,1])
    
    print('SkLearn version: {}'.format(sklearn.__version__))
    
    clf = linear_model.LogisticRegression(C=1e5)
    clf.fit(X.reshape(-1,1), y)
    
    ## -- End pasted text --
    SkLearn version: 0.19.1
    Out[41]:
    LogisticRegression(C=100000.0, class_weight=None, dual=False,
              fit_intercept=True, intercept_scaling=1, max_iter=100,
              multi_class='ovr', n_jobs=1, penalty='l2', random_state=None,
              solver='liblinear', tol=0.0001, verbose=0, warm_start=False)
    

    【讨论】:

    • 我仍然遇到同样的错误。你能告诉我你的完整代码吗?
    猜你喜欢
    • 2015-08-05
    • 2019-02-07
    • 1970-01-01
    • 2016-02-21
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2012-06-27
    相关资源
    最近更新 更多