Python 如何使用二次回归?

Python 如何使用二次回归?,python,machine-learning,scikit-learn,statsmodels,Python,Machine Learning,Scikit Learn,Statsmodels,我试图学习如何拟合二次回归模型。数据集可从以下网站下载: 让“AdjSalePrice”作为目标变量,“SQFTTOLIVING”、“SqFtLot”、“浴室”、“卧室”、“BldgGrade”作为预测变量 假设“SqFtTotLiving”将是具有2级的变量。请参阅python代码: import pandas as pd import numpy as np import statsmodels.api as sm import sklearn houses = pd.read_csv

我试图学习如何拟合二次回归模型。数据集可从以下网站下载:

让“AdjSalePrice”作为目标变量,“SQFTTOLIVING”、“SqFtLot”、“浴室”、“卧室”、“BldgGrade”作为预测变量

假设“SqFtTotLiving”将是具有2级的变量。请参阅python代码:

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] ##

如何使用sklearn和statsmodels拟合二次回归模型?我只能使用线性回归…

首先,如果X有1D数组,请执行以下操作:

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

>>>x
array([[1],
       [2],
       [3],
       [4],
       [5]])
那么这个,

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)

列车测试分割内的“结果”是什么?@EdS,应该是
y
,对不起<代码>X_序列,X_测试,y_序列,y_测试=序列测试分割(X,y,测试大小=0.33,随机状态=42)来自sklearn文档。():我得到一个错误->值错误:应该是2D数组,而不是标量数组:数组=1。使用数组重塑数据。如果数据具有单个特征或数组,则重塑(-1,1)。如果数据包含单个样本,则重塑(1,-1)。可以使用numpy重塑数据。sklearn需要2D阵列,即使它只有1D。例如,您需要的不是
[1,2,3,4]
,而是
[1]、[2]、[3]、[4]
。将此用作示例:
B=np.重塑(A,(-1,2))
,它将A重塑为2D.您的意思是
np.形状(x)
,它返回
(5647,)
?见答案,我刚刚更新