Docsity

ML Mastery Notes – SVM, Ensemble Methods & Boosting, Study notes of Technology

Partial preview of the text

Download ML Mastery Notes – SVM, Ensemble Methods & Boosting and more Study notes Technology in PDF only on Docsity!

Ce ee ee ee ee ee Suppost Vector Machine (SVM) Support Vector Machine (SVM) fs a Supervised ML algorithm thot finds the best boundasy Chyperplane”) that Sepaxates classes with the maximum plane. 3+ focuses only on the most critical points called Support Vectors, which define this boundaxny. SVM works well for both lineax and non-|fneax data using KerneQa {ike RBF ox Polynomial. 9ts goal is simple: Create tre widest Possible Separation to Reduce misclassigication . Code Example: e Linear SVM: The decision boundaxy that splits classes. e Maxgin : Distance between the hyperplane and the nearest data points. ° Support Vectors: The critica data points touching the margin — they define the boundary. e Kexnel: Technique +o handle non-linear dato by mapping it Tnto highex dimensions. Code Example: Linear SVM RBF Kernel SVM from sklearn.svm import SVC # Create and train SVM With an RBF kernel. (Gaussian) # Assume we have training data. xX, ee load _datoat) sve_rbf = SVCCkernel='rbf', C= 1.0, gamma="scale”) # Create and train SVM with a svc_rbF fit CX, 4) \tnear kernel. sve = SVC(kerned='linear') # Make predictions. svc. FfitCX, y) predictions_rbf = sve_rbf, predict + Make predictions. (X-test) predictions = svc. predict(X test) bub bedbbbbbdbbbedbbbdbbdbbbbebbddbdbdaaea BT classtCe) Class 22) at Pee DO 6 ee oe YPErPIap, 0° i : SVeo >< Zz with the eens boundary “= ye | | Support Vector Classification (_SVC) | SVC is basically the. classification version of SVM. 94+ tries to draw a boundoxy line Cin 2D) of hyperplane. Cin highex dimension) that Sepaxates two classes as widely as possible. Dt focuses only on the important points neox the the boundaxy (The Support Vectors) because they define the best sepaxating \fne. 4. Dectston function: EG) =to%+b 2. Classification Rule! * Predict class 1 if FGQ29, otherwise class 2 2. Maxgin i Mm = Woot a8 Largex maxgin — betex generalization. 4. Optimization Goal (Conceptvally ): | 2: | 2 ia ce ae ee ee ee ee eee ee ae kexnel in SVM: function that maps data fnto a highex- dimensional Space, Seeing SVMs to Find non-|fneae potteins and Separate complex dato that fsn’t Vineondky Separable in the Original Space. —> Common Kernel types 1, Linean Kernel- — Pxos: — Fast and memoxy— efficent — Less risk of ovext Hing. — Works well with misiny, features — Cons: — Cannot Captuxe complex , Non-linear patterns = Polynomial Kernel - = Pos: —~ Can model interactions between Features — More Flexible than lineax — Cons*- from skleern.svm import SVC # Polynomial Kernel # Linear Kernel clf = SVC(Kernel="poly' ,clegree=3) clf = SVC(kernel=‘lineay') clf.fit( X_Arain, y-train) clf. Fit (XAvain, y train) Ce ee ee ee ee 3. RBE (Gaussian) Kernel - — Pxos*- ae Mex Flextble — Works well fox naa yeal-wovld problems — Cons:- — Sensitive to h yperparam eters — Can overfit ff y ts too large + RBF Kernel clf = SVC (kernel='rbf’, gamma-scale’) cl. fit(X train, y_train) 4. Sigmotd Kernel — Pros - — Can mimic neural netoorKk decision Boundesies — Cons:- — Not always a valid kernel for all parameters — Often performs worse than RBF # RBF Kernel # Sigmoid Kernel elf = SVC(kernel='sigmoid’) clf = SVC(Kernel='sigmoid’) clf. fit (X_train, y_train) | elf-fit(XArain, y-train) Ye ee ee ee ee ee ee ee ee To define the “tube we look at the difference between the actual value ge and the predicted value F£CXi). The error js only calculated 7f Jui- FOU] > € +f Slack Variables Definition (20> Fox a point Yt that is above +he tube, the Uppev eurdoss is F(x) 4+ €: the distance i+ exceeds +his eet is the slack vaviable €: For points: above the tube: Ez = max (0, yi- £ (xi) - €)) For points below the tube! * = max (0, f(X1)-E- - yt) These variables allow the model to handle “errors” or outliers that cannot fit within the e-tube by paying a penalty . 4t The Optimization Function (Primal Formula) The goal of SVR is +o find a function that ts Flot as possible while Keeping the evrors (slack) +o a minimum. We minimize: min tuoi? es sé i+ef) tel a ee ee ee ee ee ee ee ee — Breaking down the Components a dati’ - “his 1s the Requlavization term. Winton 2009, this makes the weight vectors small, which ensures the function is flat and prevents over Fitting. 2. C+ Tre Bex Constratnt ( Fenobty Parameters) ° A large C means you care a lot about errors ; the model will try to fit the data very closely Crisking over fi ting) : * A smolt © means You Care about noise; flattens the model so itll be simplest Crisking underfitting ). Es See.) i- the tote sum of distances for all points falling outside the tube. + kernels And Non-linear SVR'- Most ‘real-world data is not a straight line. SVR handles this by using a kemel function +o map the data Into a higher -climensional Space where a linear Fit is possible. at The prediction Formula (Duel Ferm)!- Instead of using W-X, we often use the dual representation for calculations : £00 = (a-ak) Kix) +b tel Ce ee ee ee ee ee ee ee Ensemble Leasintng Ensemble learning iS Q machine learning technique usher e you Combine multiple individue® models Coften called “weak leamers”) to create a single, more powerful model - The core philosophy ja the Wisdom of the caousd : Just as the collective opinion of A group ts often more. accurate than that of a Single expert; an ensemble of models usually perform better than ay Single modeQ alo ne. The Core Concept: An Analogy: Imagine you vwoant to predict tf a movie will be a hit: e Single model: you ask one friend; Tf that friend has weird taste, this prediction might be ren” Chigh ervoroias* e Ensemble learning = You ask 100 friends. — Some like action, Some ITkKe mmance, Some focus on the director. e If 60 friends soy “It's geing to be a hit!” you toust the majority vote - e (he individual quirks Cerrers) of each friend Cancel each other out, leaving aA more accurate Prediction. Ce ee es ee ee ee ee eee The three main techiques. These are three primary ways to build an ensemble. 4. Bagging (Bootshrap Aggregating) « e How t+ works: You tratn multiple models in paralled CIndependently ) on different wandeom subsets of the training data- You then average thefts predictions Cfor Regression) ds take the majority vote (for claastfeatfon) © Goal: Reduces Variance Variance (prevent overfitting) e Code Samples : # For Classification from skleam.ensemble fmport BaggingClassi fier from skleamn.tree fmport DecisionTreeClassifier bag-cl£ = BaggingClassifier ( DecistonTreeClassifier(), n_estimators=100, #£ Use al| CPU cores bootstrap =True , # Use all CPU cores yandom. state =42 bag_clf.fit train, y-train) # For Regression from sklearn.ensemble import Bagging Regressor from sklearn.tree import DecisionTreeRegressor bag reg = Bagging Regressor ( DecisionTreeRegressor() , n_estimators = 100, # Sample features as well najobs =-4, # Use all CPU cores random state =42 bag_reg.fi +X train, y-train 5) Ce ee ee ee ee eee ee Splitting Criteria (the math) “To decide how te Split a node, the classifier uses metrics to Maximize Information got: 4. Gini Tmpurt: > Measurerx the likelihood of an fneorrect classification of a neu instance it it was randomly classified according. to the distribution of class labels. oe Grim Impurity is Gint,= 1- = (Peyt co! Pe = Probability of an element belonging to clase &. 2. Entropy: Measures the amount of disorder or uncertainty in the data. from sklearn.ensemble import RandomForestClassifier rf_clf = RandomForestClassifier(n_estimators=100, max_depth=10, rrandom_ state =42) rf_clf Fit X_train, y-train) ee ee ee ee ee ee ee Random Forest Regressi on used when the target Variable 7S Continuous (eg. House Prices, Temperature, Stock Value. . Working + The Structure fs nearly identical ¢do the classifier (Bootstrapping and Feature Randomness temain the Same), but the output mechanism changes - 4d. Trees ane aroun deep and unpruned. 2. Aggregation CAvexaging): To make a prediction for a nevd data Point: : Every +ree predicts a specific numeri Tcal volue. - the Forest calculates the average Cmean) of all the individual tree predictions. Splitting Critetia Che math): Since we cannot calculate “impurity” for continueus numbers In the Same Lowy, We look. at varfance. reduction . Mean Squared = CMSE): The +yee is split at He Point that minimize the avexage difference between the observed value and the predicted value. is i — G. zu Mse=1 > (Ys 4.) + Mean Absolute Exror (MAE): Sometimes used to be ouk|Teds - Pe ee a ee ee ee a ee ee 3. XGBoost / Light GBM [Cot Boost : 7) Mese are highdy optimized , moder implementations of Grad?ent Boosting . Ti) They are the ~ gold Standexd ” for tabular data competitors CKagale) because of speed ancl accuracy. XG Boost XGBoost stands for eXtreme Gradient Boosting. Tt ta an optimized distributed gradient boosting NBGn: designed to be highty efficient, and postable. 0 The “Extreme” Part: It fant just a Slightly better boosting elgoxtthion Tt ts engineered from ground up for Speed and model performance: i+ pushes the limit of odie Sas power for boosted tree algorithms . # Key Feotuxes ? ~ XGBoost improves upon Standard Gradient Boosting— (Machines, CGBM) Tn Several Critical Ways : = Regularization Standard GBMs have no intninsere Reguloxization. (expand for complexity) and can overfit easily = XGBoost includes Li (Lasso) and L2 Ridge) regularization divectty in the objective. e This prevents the model from becoming too complex and over Fitting to noise- Ce ee ee ee | Q. Parallel Proceming :- . Myth + “Boosting ts Sequential, So t+ cant be poxaltel” . Reality ‘- While the trees are bullt Sequentialty : : node Construction (Finding the best Split) tS parellelized : XGBoost Sorts and compresses data into blocks so tt can check all possible Spltts on multiple CPU cone at once. 3. Handle Missing Values : * ¥GBoost has a built-in Routine for for Missing date. * Tt learns the best disection” (left or vight) 40 send missing. values for each Split eta training . ¢ Nou don't Strictly need to impute CFill in) missing. valiuexs before Feeding data into XGBoost. 4. Twee Pruning, te « Standard GBM stops splitting ushen a node encounters a negative loss Ca greedy approach) = XGBoost grows the tree to fts maxtmam depth (defined by “max_depth’) and then prunes backwaxol , removing, Splits that didn't create a positive gain : eee ee ee ee ee ee ee ee ee ee ee ee) aBe Seeking. Suse 1S an ensemble learning technique where you trafn a meta-model to combine the predictions at several other models. Tt's based on the dea that different alges make Ai tHerent types a mistakes « By Combinin them, you Can cover up the wealkenesses of one mo votth the Strengths rat another. Working : 1. Train Base models: Train Model A, Model B, Model C 2. Create New Dotaset: Pass the tratining dota through these models to get thefr preds. 3: Train Meta-model: Train the level 1 model on this new Prediction Dataset. 4. Final Prediction : The meta-model aives the Final output. wam ing . You must use “Cross- Validation Cout-of- fold preds) to genexote the predictions for the meta-model! rf you just train on the full data and predict on the full data, the meta-learner woill Just memorize Which model overtitted the best. This ts a@ Common beginnexs mistake callecl data leakage . ee ee ee ee (419) Stacking Ceont.)* Bose Models 4+ Pros: ° Can outperform each fndividuol model by cokching- mistokes they, each make. oA great way. to get aclditional performance out of existing models + Cons: e More complex and harder to tune than just using, a single model. e Higher risk of overfiting, especially on small clatasets. Stacking Architecture : vi New Dataset! Predictions | Q) Input Data