Regression Models
Regression Models
A regression model estimates the relationship between one dependent variable (target) and one
or more independent variables (features). It helps answer questions like:
# Example data
# Split data
# Model
model = LinearRegression()
model.fit(X_train, y_train)
# Prediction
y_pred = model.predict(X_test)
# Evaluation
import numpy as np
X = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(-1, 1)
y = np.array([20, 25, 30, 38, 48, 60, 75, 90, 105, 120])
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
# Fit model
model = LinearRegression()
model.fit(X_poly, y)
# Predict
y_pred = model.predict(X_poly)
plt.xlabel('Hours Studied')
plt.ylabel('Exam Score')
plt.legend()
plt.grid(True)
plt.show()
r2 = r2_score(y, y_pred)
Ridge
import numpy as np
ridge_model = Ridge(alpha=1.0)
ridge_model.fit(X_train, y_train)
# Predict
y_pred = ridge_model.predict(X_test)
r2 = r2_score(y_test, y_pred)
print("Coefficients:", ridge_model.coef_)
print("Intercept:", ridge_model.intercept_)
import numpy as np
lasso_model = Lasso(alpha=0.1)
lasso_model.fit(X_train, y_train)
# Predict
y_pred = lasso_model.predict(X_test)
r2 = r2_score(y_test, y_pred)
print("Coefficients:", lasso_model.coef_)
print("Intercept:", lasso_model.intercept_)