使用 Polynomial/Least 平方回归预测值

Predicting values using Polynomial/Least Squares Regression

我有一个包含 2 个变量(称为 x,形状为 n x 2 个 x1 和 x2 值)和 1 个输出(称为 y)的数据集。我无法理解如何根据多项式特征和权重计算预测输出值。我的理解是 y = X dot w,其中 X 是多项式特征,w 是权重。 多项式特征是使用 sklearn.preprocessing 中的 PolynomialFeatures 生成的。权重是从 np.linalg.lstsq 生成的。下面是我为此创建的示例代码。

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

df = pd.DataFrame()
df['x1'] = [1,2,3,4,5]
df['x2'] = [11,12,13,14,15]
df['y'] = [75,96,136,170,211]

x = np.array([df['x1'],df['x2']]).T
y = np.array(df['y']).reshape(-1,1)

poly = PolynomialFeatures(interaction_only=False, include_bias=True)
poly_features = poly.fit_transform(x)
print(poly_features)
w = np.linalg.lstsq(x,y)
weight_list = []
for item in w:
  if type(item) is np.int32:
    weight_list.append(item)
    continue
  for weight in item:
    if type(weight) is np.ndarray:
      weight_list.append(weight[0])
      continue
    weight_list.append(weight)
weight_list

y_pred = np.dot(poly_features, weight_list)
print(y_pred)

regression_model = LinearRegression()
regression_model.fit(x,y)
y_predicted = regression_model.predict(x)
print(y_predicted)

对于 y_pred 值,它们与我创建的值列表相去甚远。我是否为 np.linalg.lstsq 使用了错误的输入,我的理解有误吗?

使用内置的 LinearRegression() 函数,y_predicted 更接近我提供的 y 值。 y_pred 高出几个数量级。

在lstsq函数中,生成的多项式特征应该是第一个输入,而不是最初提供的x-data。

此外,lstsq的第一个返回输出是回归coefficients/weights,可以通过索引0访问。

使用 least-squares 回归 weights/coefficients 的这种显式线性代数方法的更正代码将是:

w = np.linalg.lstsq(poly_features,y, rcond=None)
y_pred = np.dot(poly_features, w[0])

对于整个正确的代码(注意这个方法对于预测值实际上比默认的LinearRegression函数更准确):

import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
df = pd.DataFrame()
df['x1'] = [1,2,3,4,5]
df['x2'] = [11,12,13,14,15]
df['y'] = [75,96,136,170,211]

x = np.array([df['x1'],df['x2']]).T
y = np.array(df['y']).reshape(-1,1)

poly = PolynomialFeatures(interaction_only=False, include_bias=True)
poly_features = poly.fit_transform(x)
print(poly_features)
w = np.linalg.lstsq(poly_features,y, rcond=None)
print(w)

y_pred = np.dot(poly_features, w[0])
print(y_pred)

regression_model = LinearRegression()
regression_model.fit(x,y)
y_predicted = regression_model.predict(x)
print(y_predicted)