אלגוריתמים מבוססי עצים הם שיטות לימוד מכונה פופולריות המשמשות לפתרון בעיות למידה בפיקוח. אלגוריתמים אלה גמישים ויכולים לפתור כל סוג של בעיה בהישג יד (סיווג או רגרסיה).
אלגוריתמים מבוססי עצים נוטים להשתמש בממוצע לתכונות רציפות או במצב לתכונות קטגוריות בעת חיזוי על דגימות אימונים באזורים אליהם הם שייכים. הם גם מייצרים תחזיות עם רמת דיוק גבוהה , יציבות , ואת הקלות של פרשנות .
דוגמאות לאלגוריתמים מבוססי עצים
ישנם אלגוריתמים מבוססי עצים שונים שבהם אתה יכול להשתמש, כגון
- עצות החלטה
- יער אקראי
- שיפוע הדרגתי
- שקיות (צבירת Bootstrap)
אז כל מדעני נתונים צריך ללמוד את האלגוריתמים האלה ולהשתמש בהם בפרויקטים של למידת מכונה.
במאמר זה תוכלו ללמוד עוד על אלגוריתם היער האקראי. לאחר השלמת מאמר זה, עליכם להיות בקיאים בשימוש באלגוריתם היער האקראי כדי לפתור ולבנות מודלים מנבאים לבעיות סיווג בעזרת סקיקיט-לירור.
מה זה יער אקראי?
יער אקראי הוא אחד האלגוריתמים הלמידה המפוקחים המבוססים על עצים. זה גם הכי גמיש וקל לשימוש.
ניתן להשתמש באלגוריתם כדי לפתור גם בעיות סיווג וגם רגרסיה. יער אקראי נוטה לשלב מאותעצי החלטהואז מאמן כל עץ החלטה במדגם אחר של התצפיות.
התחזיות הסופיות של היער האקראי נעשות על ידי ממוצע התחזיות של כל עץ בודד.
היתרונות של יערות אקראיים הם רבים. עצי ההחלטה האינדיבידואליים נוטים להתאים יתר על המידה לנתוני האימון, אך יער אקראי יכול להקל על הבעיה על ידי ממוצע תוצאות החיזוי מעצים שונים. זה נותן ליערות אקראיים דיוק ניבוי גבוה יותר מאשר עץ החלטה יחיד.
אלגוריתם היער האקראי יכול גם לעזור לך למצוא תכונות חשובות במערך הנתונים שלך. הוא נמצא בבסיס האלגוריתם של בורוטה, הבוחר תכונות חשובות במערך נתונים.
יער אקראי שימש במגוון יישומים, למשל כדי לספק המלצות של מוצרים שונים ללקוחות במסחר אלקטרוני.
ברפואה ניתן להשתמש באלגוריתם יער אקראי לזיהוי מחלת המטופל על ידי ניתוח התיק הרפואי של המטופל.
גם בתחום הבנקאות ניתן להשתמש בו כדי לקבוע בקלות האם הלקוח הונא או לגיטימי.
כיצד עובד האלגוריתם של יער אקראי?
אלגוריתם היער האקראי עובד על ידי השלמת השלבים הבאים:
שלב 1 : האלגוריתם בחר דוגמאות אקראיות ממערך הנתונים שסופק.
שלב 2: האלגוריתם ייצור עץ החלטה עבור כל מדגם שנבחר. אז זה יקבל תוצאת חיזוי מכל עץ החלטה שנוצר.
שלב 3: ההצבעה תתבצע בכל תוצאה צפויה. לבעיית סיווג היא תשתמש במצב , ובעיית רגרסיה היא תשתמש בממוצע .
שלב 4 : ולבסוף, האלגוריתם יבחר את תוצאת החיזוי הנבחרת ביותר כחיזוי הסופי.

יער אקראי בפועל
עכשיו שאתה מכיר את העניינים והאלפים של אלגוריתם היערות האקראיים, בוא נבנה מסווג יער אקראי.
אנו בונים מסווג יער אקראי באמצעות מערך הנתונים של סוכרת Pima Indians. מערך הנתונים של סוכרת פימה אינדיאנים כולל ניבוי הופעת סוכרת תוך 5 שנים על סמך הפרטים הרפואיים המסופקים. זו בעיית סיווג בינארי.
המשימה שלנו היא לנתח וליצור מודל במאגר הנתונים של Pima Indian Diabetes כדי לחזות אם חולה מסוים נמצא בסיכון לפתח סוכרת, בהתחשב בגורמים עצמאיים אחרים.
נתחיל בייבוא חבילות חשובות בהן נשתמש לטעינת מערך הנתונים וליצור סיווג יער אקראי. נשתמש בספריית scikit-learning בכדי לטעון ולהשתמש באלגוריתם היער האקראי.
# import important packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing import StandardScaler, MinMaxScaler import pandas_profiling from matplotlib import rcParams import warnings warnings.filterwarnings("ignore") # figure size in inches rcParams["figure.figsize"] = 10, 6 np.random.seed(42)
מערך נתונים
לאחר מכן טען את מערך הנתונים מספריית הנתונים:
# Load dataset data = pd.read_csv("../data/pima_indians_diabetes.csv")
כעת אנו יכולים לצפות במדגם של מערך הנתונים.
# show sample of the dataset data.sample(5)

As you can see, in our dataset we have different features with numerical values.
Let's understand the list of features we have in this dataset.
# show columns data.columns

In this dataset, there are 8 input features and 1 output / target feature. Missing values are believed to be encoded with zero values. The meaning of the variable names are as follows (from the first to the last feature):
- Number of times pregnant.
- Plasma glucose concentration a 2 hours in an oral glucose tolerance test.
- Diastolic blood pressure (mm Hg).
- Triceps skinfold thickness (mm).
- 2-hour serum insulin (mu U/ml).
- Body mass index (weight in kg/(height in m)^2).
- Diabetes pedigree function.
- Age (years).
- Class variable (0 or 1).
Then we split the dataset into independent features and target feature. Our target feature for this dataset is called class.
# split data into input and taget variable(s) X = data.drop("class", axis=1) y = data["class"]
Preprocessing the Dataset
Before we create a model we need to standardize our independent features by using the standardScaler
method from scikit-learn.
# standardize the dataset scaler = StandardScaler() X_scaled = scaler.fit_transform(X)
You can learn more on how and why to standardize your data from this article by clicking here.
Splitting the dataset into Training and Test data
We now split our processed dataset into training and test data. The test data will be 10% of the entire processed dataset.
# split into train and test set X_train, X_test, y_train, y_test = train_test_split( X_scaled, y, stratify=y, test_size=0.10, random_state=42 )
Building the Random Forest Classifier
Now is time to create our random forest classifier and then train it on the train set. We will also pass the number of trees (100) in the forest we want to use through theparameter called n_estimators.
# create the classifier classifier = RandomForestClassifier(n_estimators=100) # Train the model using the training sets classifier.fit(X_train, y_train)

The above output shows different parameter values of the random forest classifier used during the training process on the train data.
After training we can perform prediction on the test data.
# predictin on the test set y_pred = classifier.predict(X_test)
Then we check the accuracy using actual and predicted values from the test data.
# Calculate Model Accuracy print("Accuracy:", accuracy_score(y_test, y_pred))
Accuracy: 0.8051948051948052
Our accuracy is around 80.5% which is good. But we can always make it better.
Identify Important Features
As I said before, we can also check the important features by using the feature_importances_ variable from the random forest algorithm in scikit-learn.
# check Important features feature_importances_df = pd.DataFrame( {"feature": list(X.columns), "importance": classifier.feature_importances_} ).sort_values("importance", ascending=False) # Display feature_importances_df

The figure above shows the relative importance of features and their contribution to the model. We can also visualize these features and their scores using the seaborn and matplotlib libraries.
# visualize important featuers # Creating a bar plot sns.barplot(x=feature_importances_df.feature, y=feature_importances_df.importance) # Add labels to your plt.xlabel("Feature Importance Score") plt.ylabel("Features") plt.title("Visualizing Important Features") plt.xticks( rotation=45, horizontalalignment="right", fontweight="light", fontsize="x-large" ) plt.show()

From the figure above, you can see the triceps_skinfold_thickness feature has low importance and does not contribute much to the prediction.
This means that we can remove this feature and train our random forest classifier again and then see if it can improve its performance on the test data.
# load data with selected features X = data.drop(["class", "triceps_skinfold_thickness"], axis=1) y = data["class"] # standardize the dataset scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # split into train and test set X_train, X_test, y_train, y_test = train_test_split( X_scaled, y, stratify=y, test_size=0.10, random_state=42 )
We will train the random forest algorithm with the selected processed features from our dataset, perform predictions, and then find the accuracy of the model.
# Create a Random Classifier clf = RandomForestClassifier(n_estimators=100) # Train the model using the training sets clf.fit(X_train, y_train) # prediction on test set y_pred = clf.predict(X_test) # Calculate Model Accuracy, print("Accuracy:", accuracy_score(y_test, y_pred))
Accuracy: 0.8181818181818182
Now the model accuracy has increased from 80.5% to 81.8% after we removed the least important feature called triceps_skinfold_thickness.
This suggests that it is very important to check important features and see if you can remove the least important features to increase your model's performance.
Wrapping up
Tree-based algorithms are really important for every data scientist to learn. In this article, you've learned the basics of tree-based algorithms and how to create a classification model by using the random forest algorithm.
I also recommend you try other types of tree-based algorithms such as the Extra-trees algorithm.
You can download the dataset and notebook used in this article here: //github.com/Davisy/Random-Forest-classification-Tutorial
Congratulations, you have made it to the end of this article!
If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next post! I can also be reached on Twitter @Davis_McDavid