Home > Enterprise >  I get this error "Expected 2D array, got 1D array instead "
I get this error "Expected 2D array, got 1D array instead "

Time:12-21

use this code and I get this error

"Expected 2D array, got 1D array instead"

When I want to use it with parameters of an excel table. If someone can help me, I thank you in advance.

I use all those libraries and functions for the rest of the work.

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)

CodePudding user response:

The most common error in my experience: The SK Learn only accepts 2D arrays for the x input. Use reshape

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

I think it does this for multiple regression.

Next error might be when plotting

CodePudding user response:

add it in 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() 

CodePudding user response:

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)
  • Related