【问题标题】:How to fix ValueError: Found array with 0 sample(s)如何修复 ValueError:找到包含 0 个样本的数组
【发布时间】:2018-12-06 09:01:16
【问题描述】:

当我尝试训练模型时,我对尝试使用 sklearn 运行线性回归的 python 真的很陌生:

regressIt.fit(X_train, Y_train)

它会抛出以下异常:

ValueError: Found array with 0 sample(s) (shape=(0, 546)) while a minimum of 1 is required.

我做错了什么?

提前致谢。

【问题讨论】:

  • 你有一个没有行和 546 列的二维数组,所以它基本上是空的。您需要包含重现此错误的完整代码和原始数据
  • 谢谢,这是我目前所拥有的。 import numpy as np import pandas as pd from sklearn import datasets, linear_model #获取数据 colNames = ['price', 'lotsize'] df = pd.read_csv("Housing.csv") Y = df.price.tolist() X = df.lotsize.tolist() #reshape it X=np.array(X).reshape((1,-1)) Y=np.array(Y).reshape((1,-1)) #training /testing sets X_train = X[:-250] X_test = X[-250:] # 创建线性回归对象 regressIt = linear_model.LinearRegression() # 训练模型 regressIt.fit(X_train, Y_train) #显示它 print( str(轮(regressIt.predict(Y))))
  • 将您的代码编辑到您的问题中并格式化代码
  • 添加数据和完整代码
  • import numpy as np import pandas as pd from sklearn import datasets, linear_model #获取数据 colNames = ['price', 'lotsize'] df = pd.read_csv("Housing.csv ") Y = df.price.tolist() X = df.lotsize.tolist() #重塑它 X=np.array(X).reshape((1,-1)) Y=np.array(Y)。 reshape((1,-1)) #training/testing sets X_train = X[:-250] X_test = X[-250:] Y_train = X[:-250] Y_test = Y[:-250] # 创建线性回归object regressIt = linear_model.LinearRegression() # 训练模型 regressIt.fit(X_train, Y_train) #显示它 print( str(round(regressIt.predict(Y))) )

标签: python-3.x scikit-learn


【解决方案1】:

好吧,我想我明白了
X=np.array(X).reshape((-1,1)) Should be this instead of ((1,-1)) Not sure why yet? Y=np.array(Y).reshape((-1,1)) #Also this print(str(regr.predict(X_test)))

【讨论】:

    【解决方案2】:
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3)
    # don't keep the testing data 0 i gave 30% for example,
    # for this add the next line in import
    from sklearn.model_selection import train_test_split
    

    【讨论】:

    • 您好!虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
    猜你喜欢
    • 2020-11-28
    • 2019-09-25
    • 2016-10-04
    • 2023-03-10
    • 2019-04-24
    • 1970-01-01
    • 2019-07-15
    • 2018-10-31
    • 2021-03-06
    相关资源
    最近更新 更多