【问题标题】:Found input variables with inconsistent numbers of samples when fitting LogisticRegression拟合 LogisticRegression 时发现样本数不一致的输入变量
【发布时间】:2017-12-11 15:31:07
【问题描述】:

我正在使用以下代码创建LogisticRegression 分类器:

regressor = LogisticRegression()
regressor.fit(x_train, y_train)

x_trainy_train 形状都是

<class 'tuple'>: (32383,)

x_train 包含[0..1] 范围内的值,而y_train 仅包含0s 和1s。

很遗憾,fit 失败并出现错误

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

向参数添加转置没有帮助。

【问题讨论】:

  • 尝试重塑 x_train 使其成为 (32383,1)。您得到的错误与 x_train 的形状有关
  • 我刚刚在我之前的评论之后发布了一个示例。我像你一样使用元组。如果您解决了问题,请告诉我

标签: python numpy machine-learning scikit-learn logistic-regression


【解决方案1】:

继续我在评论中提出的解决方案: 问题是 x_train 的形状。所以我们需要重塑它:

来自文档:

X : {array-like, sparse matrix}, shape (n_samples, n_features)

y : 类数组,形状 (n_samples,)

示例使用 scikit-learnnumpy

from sklearn.linear_model import LogisticRegression
import numpy as np

# create the tuple data
x_train = tuple(range(32383))
x_train = np.asarray(x_train)

#same for y_train
y_train=tuple(range(32383))
y_train = np.asarray(y_train)

#convert tuples to nparray and reshape the x_train
x_train = x_train.reshape(32383,1)

#check if shape if (32383,)
y_train.shape

#create the model
lg = LogisticRegression()

#Fit the model
lg.fit(x_train, y_train)

这应该可以正常工作。 希望对你有帮助

【讨论】:

    【解决方案2】:

    我想有点重塑是必要的。我试过这样:

        from sklearn.linear_model import LogisticRegression
        import numpy as np 
    
    
        #x_train = np.random.randn(10,1)
        x_train = np.asarray(x_train).reshape(32383,1)
        con = np.ones_like(x_train)
    
    
        x_train = np.concatenate((con,x_train), axis =1)
    
    
        #y = np.random.randn(10,1)
        #y_train = np.where(y<0.5,1,0)
        y_train = np.asarray(y_train).reshape(32383,1)
        regressor = LogisticRegression()
        regressor.fit(x_train,y_train)
    

    cmets 正是我为创建一些数据所做的。并且不要忘记在示例中添加一个常量,据我所知 sklearn 没有这样做。如果您对一些统计测试和漂亮的结果打印感兴趣,Statsmodels 也可能对您有所帮助:

        from statsmodels.api import Logit
    
        logit =Logit(y_train, x_train)
    
        fit= logit.fit()
        fit.summary()
    

    这将使您毫不费力地获得更多统计信息。

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2020-07-10
      • 2021-06-20
      • 2018-06-25
      • 1970-01-01
      • 2021-05-06
      • 2020-11-19
      • 2019-12-11
      • 2020-03-14
      相关资源
      最近更新 更多