【问题标题】:Trying to do linear Linear Regression classifier giving me "ValueError: Expected 2D array, got 1D array instead [duplicate]尝试做线性线性回归分类器给我“ValueError:预期的二维数组,而不是一维数组[重复]
【发布时间】:2019-04-30 22:06:59
【问题描述】:

我已经使用线性回归完成了 scikit-learn toturiol。当我尝试编写自己的代码来执行此操作时,我收到一条错误消息 " "如果它包含单个样本。".format(array)) ValueError:预期的 2D 数组,得到 1D 数组: "# 只使用一个特性:" 示例代码正在发送一维数组 糖尿病_X = 糖尿病.data[:, np.newaxis, 2]

这是我尝试过的: 1. 使用列表而不是 numpy 数组 2.在得到的示例代码中打印出diabetes_X [[ 0.06169621] [-0.05147406] ..... ]] 然后我尝试如下更改我的代码 xp=[[3449][1058][2201]] 得到一个错误,说预期的语句结束。 然后我尝试了 xp=[[3449],[1058],[2201]] 同样的错误信息

我的代码

xs=np.array([ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491], dtype=np.float64)
ys=np.array([529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900], dtype=np.float64)

xp=[ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491]
yp=[529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900]

clf= linear_model.LinearRegression()

clf.fit(xp, yp)
g=clf.predict( 279090)
print("+++++++ guess +++++++")
print(g)
print("jjjjjjj")

【问题讨论】:

    标签: python


    【解决方案1】:

    由于错误状态,fit 函数需要一个 2D 数组,如果您有一个特征,这意味着您有一个 1D 数组,您可以使用 reshape(1, -1) 使其成为 2D .
    这是一个工作示例:

    xs=np.array([ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491], dtype=np.float64)
    ys=np.array([529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900], dtype=np.float64)
    
    xp=[ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491]
    yp=[529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900]
    
    xp = np.array(xp).reshape(1, -1)
    yp = np.array(yp).reshape(1, -1)
    clf= linear_model.LinearRegression()
    
    clf.fit(xp, yp)
    g=clf.predict(xs.reshape(1, -1))
    print("+++++++ guess +++++++")
    print(g)
    print("jjjjjjj")
    

    【讨论】:

      【解决方案2】:

      在使用xp = np.array([....])yp = np.array([....]) 将它们转换为 NumPy 数组后,您可以将其重塑为具有单列的二维数组

      xp = xp.reshape(xp.shape[0],-1)
      yp = yp.reshape(yp.shape[0],-1)
      
      clf= linear_model.LinearRegression()
      
      clf.fit(xp, yp)
      g=clf.predict( 279090)
      print("+++++++ guess +++++++")
      print(g)
      print("jjjjjjj")
      
      # +++++++ guess +++++++
      # [[24426732.22]]
      # jjjjjjj
      

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2020-04-20
        • 2021-01-07
        • 1970-01-01
        • 2019-06-09
        • 2020-06-01
        • 2022-01-22
        • 2019-03-28
        • 2021-03-01
        相关资源
        最近更新 更多