מדריך למידת מכונה של SVM - מהו האלגוריתם של מכונת וקטור תומכת, מוסבר בדוגמאות קוד

רוב המשימות שמטפלות הלמידה במכונה כרגע כוללות דברים כמו סיווג תמונות, תרגום שפות, טיפול בכמויות גדולות של נתונים מחיישנים וניבוי ערכים עתידיים על בסיס ערכים עכשוויים. אתה יכול לבחור אסטרטגיות שונות שיתאימו לבעיה שאתה מנסה לפתור.

החדשות הטובות? יש אלגוריתם בלימוד מכונה אשר יטפל כמעט בכל הנתונים שתוכלו לזרוק אליו. אבל נגיע תוך דקה.

פיקוח לעומת למידה ללא פיקוח

שתיים מהאסטרטגיות הנפוצות ביותר בלימוד מכונה כוללות למידה מפוקחת ולמידה ללא פיקוח.

מהי למידה מפוקחת?

למידה בפיקוח היא כאשר אתה מאמן מודל למידת מכונה באמצעות נתונים שכותרתו. המשמעות היא שיש לך נתונים שכבר יש להם סיווג נכון. שימוש נפוץ אחד בלמידה בפיקוח הוא לעזור לך לחזות ערכים לנתונים חדשים.

עם למידה בפיקוח, יהיה עליך לבנות מחדש את המודלים שלך כאשר תקבל נתונים חדשים כדי לוודא שהתחזיות שהוחזרו עדיין מדויקות. דוגמה ללמידה בפיקוח תהיה תיוג תמונות של אוכל. אתה יכול לקבל מערך נתונים המוקדש רק לתמונות של פיצה כדי ללמד את המודל שלך מהי פיצה.

מהי למידה ללא פיקוח?

למידה ללא פיקוח היא כאשר אתה מאמן מודל עם נתונים ללא תווית. המשמעות היא שהמודל יצטרך למצוא תכונות משלו ולחזות על סמך האופן שבו הוא מסווג את הנתונים.

דוגמה ללמידה ללא פיקוח תהיה מתן תמונות למודל של סוגי אוכל מרובים ללא תוויות. במערך הנתונים יהיו תמונות של פיצה, צ'יפס ומזונות אחרים ותוכלו להשתמש באלגוריתמים שונים כדי לגרום למודל לזהות רק את תמונות הפיצה ללא תוויות.

אז מה אלגוריתם?

כשאתה שומע אנשים מדברים על אלגוריתמים של למידת מכונה, זכור שהם מדברים על משוואות מתמטיות שונות.

אלגוריתם הוא רק פונקציה מתמטית הניתנת להתאמה אישית. לכן לרוב האלגוריתמים יש דברים כמו פונקציות עלות, ערכי משקל ופונקציות פרמטר שתוכלו להחליף על סמך הנתונים שאתם עובדים איתם. בבסיסה, למידת מכונה היא רק חבורה של משוואות מתמטיקה שצריך לפתור ממש מהר.

זו הסיבה שיש כל כך הרבה אלגוריתמים שונים לטיפול בסוגים שונים של נתונים. אלגוריתם מסוים אחד הוא מכונת וקטור התמיכה (SVM) וזה מה שמאמר זה עתיד לסקר בפירוט.

מהו SVM?

מכונות וקטוריות תומכות הן קבוצה של שיטות למידה מפוקחות המשמשות לסיווג, רגרסיה וגילוי חריגים. כל אלה הם משימות נפוצות בלימוד מכונה.

אתה יכול להשתמש בהם לאיתור תאים סרטניים על סמך מיליוני תמונות, או להשתמש בהם כדי לחזות מסלולי נהיגה עתידיים בעזרת מודל רגרסיה מותאם היטב.

ישנם סוגים ספציפיים של SVM שבהם אתה יכול להשתמש לבעיות למידת מכונה מסוימות, כמו רגרסיה של וקטור תמיכה (SVR) המהווה הרחבה של סיווג וקטור תמיכה (SVC).

הדבר העיקרי שיש לזכור כאן הוא שמדובר רק במשוואות מתמטיות המכוונות בכדי לתת לך את התשובה המדויקת ביותר האפשרית במהירות האפשרית.

SVMs שונים מאלגוריתמי סיווג אחרים בגלל האופן שבו הם בוחרים את גבול ההחלטה שממקסם את המרחק מנקודות הנתונים הקרובות ביותר של כל הכיתות. גבול ההחלטה שנוצר על ידי SVM נקרא מסווג שוליים מקסימלי או מישור היפר מרווח מרבי.

איך עובד SVM

מסווג SVM ליניארי פשוט עובד על ידי יצירת קו ישר בין שתי כיתות. כלומר, כל נקודות הנתונים בצד אחד של הקו ייצגו קטגוריה ונקודות הנתונים בצד השני של הקו יוכנסו לקטגוריה אחרת. פירוש הדבר שיכול להיות מספר אינסופי של שורות לבחירה.

מה שהופך את אלגוריתם ה- SVM הליניארי לטוב יותר מחלק מהאלגוריתמים האחרים, כמו k השכנים הקרובים ביותר, הוא שהוא בוחר את השורה הטובה ביותר לסווג את נקודות הנתונים שלך. הוא בוחר את הקו המפריד בין הנתונים והכי רחוק מנקודות הנתונים בארון ככל האפשר.

דוגמה דו-ממדית עוזרת להבין את כל הז'רגון ללימוד מכונה. בעיקרון יש לך כמה נקודות נתונים ברשת. אתה מנסה להפריד בין נקודות נתונים אלה לפי הקטגוריה בהן הן צריכות להתאים, אך אינך מעוניין שיהיו נתונים בקטגוריה הלא נכונה. פירוש הדבר שאתה מנסה למצוא את הקו בין שתי הנקודות הקרובות ביותר המפריד בין נקודות הנתונים האחרות.

אז שתי נקודות הנתונים הקרובות ביותר נותנות לך את וקטורי התמיכה שבהם תשתמש כדי למצוא את הקו הזה. קו זה נקרא גבול ההחלטה.

גבול ההחלטה לא חייב להיות קו. זה מכונה גם hyperplan כי אתה יכול למצוא את גבול ההחלטה עם מספר כלשהו של תכונות, לא רק שתיים.

סוגי SVM

ישנם שני סוגים שונים של SVM, שכל אחד מהם משמש לדברים שונים:

  • SVM פשוט: משמש בדרך כלל לבעיות רגרסיה ליניארית וסיווג.
  • ליבה SVM: יש יותר גמישות לנתונים לא ליניאריים מכיוון שתוכל להוסיף תכונות נוספות כדי להתאים למשטח יתר במקום לחלל דו מימדי.

מדוע משתמשים ב- SVM בלימוד מכונה

משתמשים ב- SVM ביישומים כמו זיהוי כתב יד, זיהוי חדירה, זיהוי פנים, סיווג דוא"ל, סיווג גנים ובדפי אינטרנט. זו אחת הסיבות שאנו משתמשים ב- SVM בלימוד מכונה. זה יכול להתמודד עם סיווג ורגרסיה על נתונים ליניאריים ולא ליניאריים.

סיבה נוספת שאנו משתמשים ב- SVM היא מכיוון שהם יכולים למצוא קשרים מורכבים בין הנתונים שלך מבלי שתצטרך לעשות הרבה שינויים לבד. זו אפשרות נהדרת כשאתה עובד עם מערכי נתונים קטנים יותר הכוללים עשרות עד מאות אלפי תכונות. בדרך כלל הם מוצאים תוצאות מדויקות יותר בהשוואה לאלגוריתמים אחרים בגלל יכולתם להתמודד עם מערכי נתונים קטנים ומורכבים.

להלן כמה מהיתרונות והחסרונות לשימוש ב- SVM.

יתרונות

  • יעיל על מערכי נתונים עם תכונות מרובות, כמו נתונים פיננסיים או רפואיים.
  • יעיל במקרים בהם מספר התכונות גדול ממספר נקודות הנתונים.
  • משתמשת בקבוצת משנה של נקודות אימון בפונקציית ההחלטה הנקראת וקטורי תמיכה מה שהופך אותה ליעילה בזיכרון.
  • ניתן לציין פונקציות ליבה שונות עבור פונקציית ההחלטה. אתה יכול להשתמש בגרעינים נפוצים, אך ניתן גם לציין גרעינים מותאמים אישית.

חסרונות

  • אם מספר התכונות גדול בהרבה ממספר נקודות הנתונים, הימנעות מהתאמה יתרה בבחירת פונקציות הליבה ומונח הסדרה היא קריטית.
  • SVMs אינם מספקים הערכות הסתברות ישירות. אלה מחושבים באמצעות אימות צולב יקר פי חמש.
  • עובד הכי טוב על ערכות דוגמה קטנות בגלל זמן האימון הגבוה שלו.

מכיוון ש- SVM יכולים להשתמש בכל מספר גרעינים, חשוב שתדעו על כמה מהם.

פונקציות ליבה

לינארי

אלה מומלצים בדרך כלל לסיווג טקסט מכיוון שרוב סוגים אלה של בעיות סיווג ניתנות להפרדה ליניארית.

The linear kernel works really well when there are a lot of features, and text classification problems have a lot of features. Linear kernel functions are faster than most of the others and you have fewer parameters to optimize.

Here's the function that defines the linear kernel:

f(X) = w^T * X + b

In this equation, w is the weight vector that you want to minimize, X is the data that you're trying to classify, and b is the linear coefficient estimated from the training data. This equation defines the decision boundary that the SVM returns.

Polynomial

The polynomial kernel isn't used in practice very often because it isn't as computationally efficient as other kernels and its predictions aren't as accurate.

Here's the function for a polynomial kernel:

f(X1, X2) = (a + X1^T * X2) ^ b

This is one of the more simple polynomial kernel equations you can use. f(X1, X2) represents the polynomial decision boundary that will separate your data. X1 and X2 represent your data.

Gaussian Radial Basis Function (RBF)

One of the most powerful and commonly used kernels in SVMs. Usually the choice for non-linear data.

Here's the equation for an RBF kernel:

f(X1, X2) = exp(-gamma * ||X1 - X2||^2)

In this equation, gamma specifies how much a single training point has on the other data points around it. ||X1 - X2|| is the dot product between your features.

Sigmoid

More useful in neural networks than in support vector machines, but there are occasional specific use cases.

Here's the function for a sigmoid kernel:

f(X, y) = tanh(alpha * X^T * y + C)

In this function, alpha is a weight vector and C is an offset value to account for some mis-classification of data that can happen.

Others

There are plenty of other kernels you can use for your project. This might be a decision to make when you need to meet certain error constraints, you want to try and speed up the training time, or you want to super tune parameters.

Some other kernels include: ANOVA radial basis, hyperbolic tangent, and Laplace RBF.

Now that you know a bit about how the kernels work under the hood, let's go through a couple of examples.

Examples with datasets

To show you how SVMs work in practice, we'll go through the process of training a model with it using the Python Scikit-learn library. This is commonly used on all kinds of machine learning problems and works well with other Python libraries.

Here are the steps regularly found in machine learning projects:

  • Import the dataset
  • Explore the data to figure out what they look like
  • Pre-process the data
  • Split the data into attributes and labels
  • Divide the data into training and testing sets
  • Train the SVM algorithm
  • Make some predictions
  • Evaluate the results of the algorithm

Some of these steps can be combined depending on how you handle your data. We'll do an example with a linear SVM and a non-linear SVM. You can find the code for these examples here.

Linear SVM Example

We'll start by importing a few libraries that will make it easy to work with most machine learning projects.

import matplotlib.pyplot as plt import numpy as np from sklearn import svm

For a simple linear example, we'll just make some dummy data and that will act in the place of importing a dataset.

# linear data X = np.array([1, 5, 1.5, 8, 1, 9, 7, 8.7, 2.3, 5.5, 7.7, 6.1]) y = np.array([2, 8, 1.8, 8, 0.6, 11, 10, 9.4, 4, 3, 8.8, 7.5])

The reason we're working with numpy arrays is to make the matrix operations faster because they use less memory than Python lists. You could also take advantage of typing the contents of the arrays. Now let's take a look at what the data look like in a plot:

# show unclassified data plt.scatter(X, y) plt.show()

Once you see what the data look like, you can take a better guess at which algorithm will work best for you. Keep in mind that this is a really simple dataset, so most of the time you'll need to do some work on your data to get it to a usable state.

We'll do a bit of pre-processing on the already structured code. This will put the raw data into a format that we can use to train the SVM model.

# shaping data for training the model training_X = np.vstack((X, y)).T training_y = [0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1]

Now we can create the SVM model using a linear kernel.

# define the model clf = svm.SVC(kernel='linear', C=1.0)

That one line of code just created an entire machine learning model. Now we just have to train it with the data we pre-processed.

# train the model clf.fit(training_X, training_y)

That's how you can build a model for any machine learning project. The dataset we have might be small, but if you encounter a real-world dataset that can be classified with a linear boundary this model still works.

With your model trained, you can make predictions on how a new data point will be classified and you can make a plot of the decision boundary. Let's plot the decision boundary.

# get the weight values for the linear equation from the trained SVM model w = clf.coef_[0] # get the y-offset for the linear equation a = -w[0] / w[1] # make the x-axis space for the data points XX = np.linspace(0, 13) # get the y-values to plot the decision boundary yy = a * XX - clf.intercept_[0] / w[1] # plot the decision boundary plt.plot(XX, yy, 'k-') # show the plot visually plt.scatter(training_X[:, 0], training_X[:, 1], c=training_y) plt.legend() plt.show()

Non-Linear SVM Example

For this example, we'll use a slightly more complicated dataset to show one of the areas SVMs shine in. Let's import some packages.

import matplotlib.pyplot as plt import numpy as np from sklearn import datasets from sklearn import svm

This set of imports is similar to those in the linear example, except it imports one more thing. Now we can use a dataset directly from the Scikit-learn library.

# non-linear data circle_X, circle_y = datasets.make_circles(n_samples=300, noise=0.05)

The next step is to take a look at what this raw data looks like with a plot.

# show raw non-linear data plt.scatter(circle_X[:, 0], circle_X[:, 1], c=circle_y, marker=".") plt.show()

Now that you can see how the data are separated, we can choose a non-linear SVM to start with. This dataset doesn't need any pre-processing before we use it to train the model, so we can skip that step. Here's how the SVM model will look for this:

# make non-linear algorithm for model nonlinear_clf = svm.SVC(kernel='rbf', C=1.0)

In this case, we'll go with an RBF (Gaussian Radial Basis Function) kernel to classify this data. You could also try the polynomial kernel to see the difference between the results you get. Now it's time to train the model.

# training non-linear model nonlinear_clf.fit(circle_X, circle_y)

You can start labeling new data in the correct category based on this model. To see what the decision boundary looks like, we'll have to make a custom function to plot it.

# Plot the decision boundary for a non-linear SVM problem def plot_decision_boundary(model, ax=None): if ax is None: ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() # create grid to evaluate model x = np.linspace(xlim[0], xlim[1], 30) y = np.linspace(ylim[0], ylim[1], 30) Y, X = np.meshgrid(y, x) # shape data xy = np.vstack([X.ravel(), Y.ravel()]).T # get the decision boundary based on the model P = model.decision_function(xy).reshape(X.shape) # plot decision boundary ax.contour(X, Y, P, levels=[0], alpha=0.5, linestyles=['-'])

You have everything you need to plot the decision boundary for this non-linear data. We can do that with a few lines of code that use the Matlibplot library, just like the other plots.

# plot data and decision boundary plt.scatter(circle_X[:, 0], circle_X[:, 1], c=circle_y, s=50) plot_decision_boundary(nonlinear_clf) plt.scatter(nonlinear_clf.support_vectors_[:, 0], nonlinear_clf.support_vectors_[:, 1], s=50, lw=1, facecolors="none") plt.show()

When you have your data and you know the problem you're trying to solve, it really can be this simple.

You can change your training model completely, you can choose different algorithms and features to work with, and you can fine tune your results based on multiple parameters. There are libraries and packages for all of this now so there's not a lot of math you have to deal with.

Tips for real world problems

Real world datasets have some common issues because of how large they can be, the varying data types they hold, and how much computing power they can need to train a model.

There are a few things you should watch out for with SVMs in particular:

  • Make sure that your data are in numeric form instead of categorical form. SVMs expect numbers instead of other kinds of labels.
  • Avoid copying data as much as possible. Some Python libraries will make duplicates of your data if they aren't in a specific format. Copying data will also slow down your training time and skew the way your model assigns the weights to a specific feature.
  • Watch your kernel cache size because it uses your RAM. If you have a really large dataset, this could cause problems for your system.
  • Scale your data because SVM algorithms aren't scale invariant. That means you can convert all of your data to be within the ranges of [0, 1] or [-1, 1].

Other thoughts

You might wonder why I didn't go into the deep details of the math here. It's mainly because I don't want to scare people away from learning more about machine learning.

It's fun to learn about those long, complicated math equations and their derivations, but it's rare you'll be writing your own algorithms and writing proofs on real projects.

It's like using most of the other stuff you do every day, like your phone or your computer. You can do everything you need to do without knowing the how the processors are built.

Machine learning is like any other software engineering application. There are a ton of packages that make it easier for you to get the results you need without a deep background in statistics.

Once you get some practice with the different packages and libraries available, you'll find out that the hardest part about machine learning is getting and labeling your data.

I'm working on a neuroscience, machine learning, web-based thing! You should follow me on Twitter to learn more about it and other cool tech stuff.