【问题标题】:How to use quadratic regression?如何使用二次回归?
【发布时间】:2020-03-12 00:35:59
【问题描述】:

我正在尝试学习如何拟合二次回归模型。数据集可以从以下位置下载: https://filebin.net/ztr9har5nio7x78v

设“AdjSalePrice”为目标变量,“SqFtTotLiving”、“SqFtLot”、“Bathrooms”、“Bedrooms”、“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 拟合二次回归模型?我只能用线性回归...

【问题讨论】:

    标签: python machine-learning scikit-learn statsmodels


    【解决方案1】:

    首先,如果您有一个 X 的一维数组,请执行以下操作:

    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)
    

    【讨论】:

    • train_test_split 中的“结果”是什么?
    • @EdS,应该是y,抱歉。 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) 来自 sklearn 文档。 (scikit-learn.org/stable/modules/generated/…)
    • :我得到一个错误 -> ValueError:预期的 2D 数组,得到的是标量数组:array=1。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)。
    • 你可以使用 numpy 来重塑它。 sklearn 需要二维数组,即使它只有一维。例如,您需要[[1], [2], [3], [4]],而不是[1,2,3,4]。将此作为示例:B = np.reshape(A, (-1, 2)),它将 A 重塑为 2D。
    • 你的意思是np.shape(x),它返回(5647,)?看答案,我刚刚更新了
    猜你喜欢
    • 2018-09-04
    • 2016-08-17
    • 1970-01-01
    • 2012-06-07
    • 2016-02-16
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多