22 Practice Polynomial Regression
22 Practice Polynomial Regression
import numpy as np
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([3, 5, 7, 9, 11])
model = LinearRegression()
model.fit(X, y)
# Make predictions
y_pred = model.predict(X)
plt.legend()
plt.show()
X_multi = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
model_multi = LinearRegression()
model_multi.fit(X_train, y_train)
# Model evaluation
degree = 2
poly = PolynomialFeatures(degree=degree)
X_poly_transformed = poly.fit_transform(X_poly)
model_poly = LinearRegression()
model_poly.fit(X_poly_transformed, y_poly)
# Predictions
y_poly_pred = model_poly.predict(X_poly_transformed)
plt.legend()
plt.show()
degree = 3
poly = PolynomialFeatures(degree=degree)
X_poly_transformed = poly.fit_transform(X_poly)
model_poly = LinearRegression()
model_poly.fit(X_poly_transformed, y_poly)
# Predictions
y_poly_pred = model_poly.predict(X_poly_transformed)
plt.legend()
plt.show()
ridge_model = Ridge(alpha=1.0)
ridge_model.fit(X_train, y_train)
lasso_model = Lasso(alpha=0.1)
lasso_model.fit(X_train, y_train)
poly_multi = PolynomialFeatures(degree=2)
X_multi_poly = poly_multi.fit_transform(X_multi)
model_multi_poly = LinearRegression()
model_multi_poly.fit(X_multi_poly, y_multi)
scaler = StandardScaler()
X_multi_scaled = scaler.fit_transform(X_multi)
model_multi_scaled = LinearRegression()
model_multi_scaled.fit(X_multi_scaled, y_multi)
print('Scaled Multivariate Coefficients:', model_multi_scaled.coef_)
X_poly_scaled = scaler.fit_transform(X_poly)
model_poly_scaled = LinearRegression()
model_poly_scaled.fit(X_poly_scaled, y_poly)
model_regularized_poly.fit(X_poly, y_poly)
Linear Regression
1. Basic Linear Regression: Train a linear regression model to predict house prices based
on the number of rooms and the area of the house. Use a synthetic dataset with at least
100 samples.
2. Performance Evaluation: Calculate the Mean Squared Error (MSE) and R² score for a
linear regression model trained on a real-world dataset like the Boston Housing dataset.
Multivariate Regression
3. Predicting Car Prices: Use multivariate linear regression to predict car prices based on
features like horsepower, mileage, and engine size.
4. Feature Impact Analysis: Train a multivariate model on a synthetic dataset and analyze
the impact of each feature using the learned coefficients.
Polynomial Regression
Multivariate Polynomial Regression: Use a dataset with multiple features (e.g., stock prices,
weather data) to fit a second-degree polynomial regression model.