1
votes

I am new to machine learning and facing some issues in converting scalar array to 2d array. I am trying to implement polynomial regression in spyder. Here is my code, Please help!

# Polynomial Regression

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X)
poly_reg.fit(X_poly, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

# Predicting a new result with Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5))

ValueError: Expected 2D array, got scalar array instead: array=6.5. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

3
which line you get this error?Jeril

3 Answers

3
votes

You get this issue in Jupyter only. To resolve in jupyter make the value into np array using below code.

lin_reg.predict(np.array(6.5).reshape(1,-1))
lin_reg_2.predict(poly_reg.fit_transform(np.array(6.5).reshape(1,-1)))

For spyder it work same as you expected:

lin_reg.predict(6.5)
lin_reg_2.predict(poly_reg.fit_transform(6.5))
0
votes

The issue with your code is linreg.predict(6.5).

If you read the error statement it says that the model requires a 2-d array , however 6.5 is scalar. Why? If you see your X data is having 2-d so anything that you want to predict with your model should also have two 2d shape. This can be achieved either by using .reshape(-1,1) which creates a column vector (feature vector) or .reshape(1,-1) If you have single sample.

Things to remember in order to predict I need to prepare my data in the same way as my original training data.

If you need any more info let me know.

0
votes

You have to give the input as 2D array, Hence try this!

lin_reg.predict([6.5])
lin_reg_2.predict(poly_reg.fit_transform([6.5]))