【问题标题】:Training data in a training set训练集中的训练数据
【发布时间】:2020-01-31 14:46:48
【问题描述】:

我正在尝试使用 scikit-learn 在我的训练集中训练一个模型,但出现此错误:

 ValueError: Expected 2D array, got 1D array instead: array=[90.  4.].
 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.

第 1 步:将 x 和 y 拆分为训练和测试集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.4, random_state = 4)

检查新拆分的 x 值的形状(训练和测试)

X_train = X_train.shape
X_test = X_test.shape
print(X_train)
print(X_test)

检查新分割的 y 值的形状(训练和测试)

y_train = y_train.shape
y_test = y_test.shape
print(y_train)
print(y_test)

第 2 步:在训练集上训练我们的模型(使用逻辑回归)

logR = LogisticRegression()
logR = logR.fit(X_train, y_train)

运行这段代码我得到了错误

【问题讨论】:

    标签: python scikit-learn data-science


    【解决方案1】:

    您似乎正在用它们的形状替换数据点:

    X_train = X_train.shape
    X_test = X_test.shape
    y_train = y_train.shape
    y_test = y_test.shape
    

    删除这些行并重新运行。

    【讨论】:

      【解决方案2】:

      您做得很好,但您做错了一件事:您将训练和测试数据替换为 1D 形状,这就是您面临此错误的原因

       #replace these line
      
      from sklearn.model_selection import train_test_split
      X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.4, random_state = 4)
      
      print( X_train.shape)
      print( X_test.shape)
      print(y_train.shape)
      print(y_test.shape)
      
      logR = LogisticRegression()
      logR = logR.fit(X_train, y_train)
      
      # Now it work fine
      

      【讨论】:

        猜你喜欢
        • 2017-07-07
        • 2014-07-22
        • 2017-12-12
        • 2023-03-26
        • 2019-09-30
        • 2016-06-08
        • 2015-08-14
        • 2022-11-17
        • 2018-05-01
        相关资源
        最近更新 更多