我应该如何在python中使用rsquare和mse在多项式回归评估中定义y_true

问题描述 投票:0回答:1
from sklearn.preprocessing import PolynomialFeatures
train_x_p = np.asanyarray(train[['FUELCONSUMPTION_COMB_MPG']])
poly = PolynomialFeatures(degree = 3)
train_x_poly = poly.fit_transform(train_x_p)
regr.fit(train_x_poly, train_y)
print('Coefficients: ', regr.coef_)
print('Intercept', regr.intercept_)

test_x_poly = poly.fit_transform(test_x)
test_y_poly1 = np.asanyarray(test[['CO2EMISSIONS']]) #im not sure especially about this line 
test_y_hat_poly1 = regr.predict(test_x_poly)

mse = metrics.mean_squared_error(test_y_poly1, test_y_hat_poly1)
r2 = (r2_score(test_y_poly1,test_y_hat_poly1))
print('MSE&R2SQUARE polynomial linear regression (FUELCONSUMPTION_COMB_MPG): ')
print('MSE: ',mse)
print('r2-sq: ',r2)

也是让我感到不正确的原因,MSE的结果在这里输入代码我应该将测试y转换为poly,如果应该怎么做?

python machine-learning linear-regression polynomial-math
1个回答
1
投票
否,您不应该转换y_true值。多项式特征的作用是,它采用x_1, x_2, ..., x_p个预测变量,并对每个预测变量应用选定程度的多项式变换。

如果您有2个预测变量x_1 and x_2并应用3次多项式变换,则会遇到以下形式的问题:

y = b_0 + b_1 * x_1 + b_2 * x_1^2 + b_3 * x_1^3 + b_4 * x_2 + b_5 * x_2^2 + b_6 * x_2^3

当预测变量与响应之间存在非线性关系并且要使用线性模型拟合数据时,您要执行此操作。无论您是否使用多项式特征(或大多数其他回归模型),y_true都保持不变。

您的代码几乎可以用,除了一个问题-您正在测试数据上调用fit_transform,这是您永远都不想做的。您已经在训练数据上拟合了多项式特征对象,您所要做的就是调用transform方法来转换测试数据。

test_x_poly = poly.transform(test_x)


这里是一个示例,当预测变量和响应之间存在多项式关系时,使用多项式特征时的外观。

    获取数据(我将生成一些数据)
  • X = np.random.randint(-100, 100, (100, 1)) y = X ** 2 + np.random.normal(size=(100, 1))
      训练/测试分组
  • X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      在火车数据上拟合多项式特征
  • poly_features = PolynomialFeatures(degree=2) X_train_poly = poly_features.fit_transform(X_train) # transform the data as well
      将线性回归模型拟合到火车数据上
  • reg = LinearRegression() reg.fit(X_train_poly, y_train)
      ((仅用于说明目的-可视化回归线-仅在只有一个预测变量时适用)
  • reg_line_x = poly_features.transform(np.linspace(-100, 100, 1000).reshape((-1, 1))) reg_line_y = reg.predict(reg_line_x) plt.scatter(X_train_poly[:, 1].ravel(), y_train) plt.plot(reg_line_x[:, 1].ravel(), reg_line_y, c="red", label="regression line") plt.legend() plt.show()
    enter image description here

      转换X_test数据并进行预测
  • # do NOT call fit_transform here X_test_poly = poly_features.transform(X_test) y_pred = reg.predict(X_test_poly)

    还有一种更方便的方法,即建立一个处理所有内容的管道(在您的情况下是多项式变换和回归),因此您不必手动执行每个步骤。

    from sklearn.pipeline import Pipeline pipe = Pipeline([ ("poly_features", poly_features), ("regression", reg) ]) y_pred = pipe.predict(X_test) print(f"r2 : {r2_score(y_test, y_pred)}") print(f"mse: {mean_squared_error(y_test, y_pred)}")

    r2:0.9999997923643911

    mse:1.4848830127345198


    请注意,在您的情况下,r平方或MSE显示差的值并不意味着您的代码是错误的。可能是您的数据不适合该任务的情况,或者您需要使用不同程度的多项式变换-您可能不足或过度拟合了训练数据等。
  • © www.soinside.com 2019 - 2024. All rights reserved.