【问题标题】:Sklearn : ValueError: Found input variables with inconsistent numbers of samples: [1, 6]Sklearn:ValueError:发现样本数量不一致的输入变量:[1, 6]
【发布时间】:2017-10-26 04:08:14
【问题描述】:
X = [ 1994.  1995.  1996.  1997.  1998.  1999.]
y = [1.2 2.3 3.4 4.5 5.6 6.7]
clf = LinearRegression()
clf.fit(X,y)

这给出了上述错误。 X 和 y 都是 numpy 数组

如何消除此错误?

我尝试了给定here 的方法,并使用X.reshape((-1,1))y.reshape((-1,1)) 重塑了X 和y。但是没有成功。

【问题讨论】:

  • 你是如何用这种语法声明一个 numpy 数组的?这些值必须用逗号分隔,也可以是单个值。你可以使用 X = [ 1994, 1995, 1996, 1997, 1998, 1999]
  • 使用 X.reshape(-1,1) 重塑 X,无需重塑 y。
  • ` a = [ 1994, 1995, 1996, 1997, 1998, 1999] ` X=np.array(a)`。对 y 类似。当我打印 X 时,它给出了我所显示的内容

标签: python scikit-learn


【解决方案1】:

这对我来说很好。在重塑之前,请确保数组是 numpy 数组。

import numpy as np
from sklearn.linear_model import LinearRegression

X = np.asarray([ 1994.,  1995.,  1996.,  1997.,  1998.,  1999.])
y = np.asarray([1.2, 2.3, 3.4, 4.5, 5.6, 6.7])

clf = LinearRegression()
clf.fit(X.reshape(-1,1),y)


clf.predict([1997])
#Output: array([ 4.5])

clf.predict([2001])
#Output: array([ 8.9])

【讨论】:

    【解决方案2】:
    import pandas as pd
    import numpy as np
    from sklearn import linear_model
    from sklearn.cross_validation import train_test_split
    
    df_house = pd.read_csv('CSVFiles/kc_house_data.csv',index_col = 0,engine ='c')
    
    df_house.drop(df_house.columns[[1, 0, 10, 11,12, 13, 14, 15, 16, 17,18]], axis=1, inplace=True)
    
    reg=linear_model.LinearRegression()
    df_y=df_house[df_house.columns[1:2]]
    
    
    df_house.drop(df_house.columns[[6, 7, 8, 5]], axis=1, inplace=True)
    
    
    x_train, x_test, y_train, y_test=train_test_split(df_house, df_y, test_size=0.1, random_state=7)
    
    print(x_train.shape, y_train.shape)
    
    reg.fit(x_train, x_test)
    
    LinearRegression(copy_x=True, fit_intercept=True, n_jobs=1, normalize=False )
    
    My Shape is :
    (19451, 5) (19451, 1)
    
    ValueError: Found input variables with inconsistent numbers of samples: [19451, 2162]
    

    【讨论】:

      猜你喜欢
      • 2019-06-06
      • 2020-07-05
      • 2023-03-22
      • 2021-08-18
      • 2018-01-23
      • 2022-01-16
      • 2021-07-29
      • 2020-11-15
      • 2021-10-09
      相关资源
      最近更新 更多