【问题标题】:I get this error "Expected 2D array, got 1D array instead "我收到此错误“预期的二维数组,而不是一维数组”
【发布时间】:2022-01-22 08:19:48
【问题描述】:

使用此代码,我收到此错误

"预期的二维数组,得到一维数组"

当我想将它与 Excel 表的参数一起使用时。如果有人可以帮助我,我提前感谢您。

我将所有这些库和函数用于其余工作。

import numpy as np
import pandas as pd
import sympy as sp
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures 
    def R_Lineal1(x,y):
      lin = LinearRegression()
      lin.fit(x, y)
      plt.scatter(x, y, color = 'blue') 
      plt.plot(x, lin.predict(x), color = 'red')
      plt.title('Regresión Lineal, PWV v/s Módulo de Elasticidad')
      plt.xlabel('PWV [m/s]') 
      plt.ylabel('ME [MPa]') 
      plt.grid()
      plt.show() 
R_Lineal1(PWV_C,ME_C)

【问题讨论】:

  • R_Lineal1(PWV_C,ME_C)我的代码结束
  • 什么是 PWV_C、ME_C?
  • 它们是从 excel 中提取的数字列

标签: python python-3.x jupyter-notebook jupyter jupyter-lab


【解决方案1】:

在def中添加

def R_Lineal1(x,y):
  x = np.reshape(x, (len(x), 1))
  lin = LinearRegression()
  lin.fit(x, y)
  plt.scatter(x, y, color = 'blue') 
  plt.plot(x, lin.predict(x), color = 'red')
  plt.title('Regresión Lineal, PWV v/s Módulo de Elasticidad')
  plt.xlabel('PWV [m/s]') 
  plt.ylabel('ME [MPa]') 
  plt.grid()
  plt.show() 

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:
import numpy as np
import pandas as pd
import sympy as sp
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures 
    def R_Lineal1(x,y):

      x_train_new = x.to_numpy().reshape(-1,1) #update

      lin = LinearRegression()
      lin.fit(x, y)
      plt.scatter(x, y, color = 'blue') 
      plt.plot(x, lin.predict(x), color = 'red')
      plt.title('Regresión Lineal, PWV v/s Módulo de Elasticidad')
      plt.xlabel('PWV [m/s]') 
      plt.ylabel('ME [MPa]') 
      plt.grid()
      plt.show() 
R_Lineal1(PWV_C,ME_C)

【讨论】:

  • @Pipe 如果我或其他用户的回答是您问题的解决方案,请接受 Stackoverflow 帮助中心规则的回答,谢谢
【解决方案3】:

我的经验中最常见的错误:SK Learn 只接受 x 输入的二维数组。使用重塑

    x_train = x.to_numpy().reshape(-1,1)

我认为它可以用于多重回归,因为它可以有多个输入。

【讨论】:

  • 在添加你所说的内容时,我收到了这个新错误“数据必须是一维的”
  • 你在哪里添加的?
  • @gotenks 恕我直言x = x.reshape(-1, 1) 更简单。
  • 这更简单,你
  • 使用它,我得到这个错误“'Series' object has no attribute 'reshape'”
猜你喜欢
  • 2019-03-28
  • 2020-06-01
  • 2018-01-15
  • 2020-05-11
  • 2023-03-07
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多