GamerBhai02

ML Exp 2

Sep 15th, 2025 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | Source Code | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from sklearn.preprocessing import StandardScaler
  5. from sklearn.linear_model import Ridge, Lasso
  6. from sklearn.model_selection import train_test_split
  7. from sklearn.metrics import mean_squared_error, r2_score
  8. df = pd.read_csv("Advertising.csv")
  9. df = df.iloc[:, 1:]
  10. display(df.head())
  11. X=df.drop("sales",axis=1)
  12. y=df["sales"]
  13. X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
  14. scaler = StandardScaler()
  15. X_train_scaled = scaler.fit_transform(X_train)
  16. X_test_scaled = scaler.transform(X_test)
  17. # Ridge Regression
  18. ridge = Ridge()
  19. ridge.fit(X_train_scaled, y_train)
  20. # Lasso Regression
  21. lasso = Lasso()
  22. lasso.fit(X_train_scaled, y_train)
  23. ridge_preds = ridge.predict(X_test_scaled)
  24. ridge_mse = mean_squared_error(y_test, ridge_preds)
  25. ridge_r2 = r2_score(y_test, ridge_preds)
  26.  
  27. lasso_preds = lasso.predict(X_test_scaled)
  28. lasso_mse = mean_squared_error(y_test, lasso_preds)
  29. lasso_r2 = r2_score(y_test, lasso_preds)
  30.  
  31. print("πŸ“Š Model Comparison:")
  32. if ridge_mse < lasso_mse:
  33.     print(f"βœ… Ridge has lower MSE ({ridge_mse:.4f}) than Lasso ({lasso_mse:.4f})")
  34. else:
  35.     print(f"βœ… Lasso has lower MSE ({lasso_mse:.4f}) than Ridge ({ridge_mse:.4f})")
  36.  
  37. if ridge_r2 > lasso_r2:
  38.     print(f"βœ… Ridge has higher RΒ² Score ({ridge_r2:.4f}) than Lasso ({lasso_r2:.4f})")
  39. else:
  40.     print(f"βœ… Lasso has higher RΒ² Score ({lasso_r2:.4f}) than Ridge ({ridge_r2:.4f})")
  41.  
  42. ridge_coef= ridge.coef_
  43. lasso_coef = lasso.coef_
  44. plt.plot(ridge_coef,'s',label="Ridge Coefficients")
  45. plt.plot(lasso_coef,'x',label="Lasso Coefficients")
  46. plt.xlabel("Coefficient index")
  47. plt.ylabel("Coefficient magnitude")
  48. plt.title("Comparison of Ridge and Lasso coefficients")
  49. plt.legend()
  50. plt.show()
Tags: ML
Advertisement
Add Comment
Please, Sign In to add comment