0
votes

I am trying to learn how to fit a quadratic regression model. The dataset can be downloaded from: https://filebin.net/ztr9har5nio7x78v

Let be "AdjSalePrice" the target variable and "SqFtTotLiving", "SqFtLot", "Bathrooms", "Bedrooms", "BldgGrade" the predictor variables.

Imagine that "SqFtTotLiving" will be the variable that will have the degree 2. Be the python code:

import pandas as pd
import numpy as np
import statsmodels.api as sm
import sklearn


houses = pd.read_csv("house_sales.csv", sep = '\t')#separador é tab

colunas = ["AdjSalePrice","SqFtTotLiving","SqFtLot","Bathrooms","Bedrooms","BldgGrade"]

houses1 = houses[colunas]


X = houses1.iloc[:,1:] ## 
y =  houses1.iloc[:,0] ##

How to fit a quadratic regression model using sklearn and statsmodels? I can only use linear regression ...

1

1 Answers

1
votes

First if you have a 1D array for X, do this:

x = np.array([1,2,3,4,5])
x = x.reshape((-1,1))

Result:

>>>x
array([[1],
       [2],
       [3],
       [4],
       [5]])

Then this:

from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model

poly = PolynomialFeatures(degree=2)
poly_variables = poly.fit_transform(x)

poly_var_train, poly_var_test, res_train, res_test = train_test_split(poly_variables, y, test_size = 0.3, random_state = 4)

regression = linear_model.LinearRegression()

model = regression.fit(poly_var_train, res_train)
testing_score = model.score(poly_var_test, res_test)