Extract coefficients from a regression model to manually calculate predictions
Question:
I have a large set of data points, which I would like to transform using coefficients. Instead of applying a linear regression prediction y_pred
for each element, I want extract coefficient and use them like matrix*coef1 + matrix**coef2
etc.
x=np.array([[0.25],[0.35],[0.45],[0.55],[0.65],[0.75],[0.85],[0.95]])
y=np.array([[81.2198],[77.882 ],[74.5442],[72.319],[70.6501],[67.8686],[67.3123],[65.6434]])
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.125, random_state=42)
degree = 3
# Create a pipeline with a polynomial feature transformation and linear regression
model = make_pipeline(
PolynomialFeatures(degree=degree, include_bias=False),
LinearRegression()
)
# Fit the model to the training data
model.fit(x_train, y_train)
# Make predictions on the test data
y_pred = model.predict(x_test)
# Calculate the absolute error
abs_error_array = np.array(np.abs((y_test - y_pred)))
# Get the coefficients of the linear regression model
linreg_coef = model.named_steps['linearregression'].coef_
# Print the coefficients
print(linreg_coef)
If I use these coefficients, the result does not match model.predict for a new input value.
How to get the coefficients suitable for manual calculation?
Answers:
The linear regression has an intercept:
model.named_steps['linearregression'].intercept_
which you need to add. Then the result will fit (I checked).
I have a large set of data points, which I would like to transform using coefficients. Instead of applying a linear regression prediction y_pred
for each element, I want extract coefficient and use them like matrix*coef1 + matrix**coef2
etc.
x=np.array([[0.25],[0.35],[0.45],[0.55],[0.65],[0.75],[0.85],[0.95]])
y=np.array([[81.2198],[77.882 ],[74.5442],[72.319],[70.6501],[67.8686],[67.3123],[65.6434]])
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.125, random_state=42)
degree = 3
# Create a pipeline with a polynomial feature transformation and linear regression
model = make_pipeline(
PolynomialFeatures(degree=degree, include_bias=False),
LinearRegression()
)
# Fit the model to the training data
model.fit(x_train, y_train)
# Make predictions on the test data
y_pred = model.predict(x_test)
# Calculate the absolute error
abs_error_array = np.array(np.abs((y_test - y_pred)))
# Get the coefficients of the linear regression model
linreg_coef = model.named_steps['linearregression'].coef_
# Print the coefficients
print(linreg_coef)
If I use these coefficients, the result does not match model.predict for a new input value.
How to get the coefficients suitable for manual calculation?
The linear regression has an intercept:
model.named_steps['linearregression'].intercept_
which you need to add. Then the result will fit (I checked).