Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»AI & Machine Learning»Support Vector Machine (SVM) in Machine Learning: An Interactive Guide
    AI & Machine Learning

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    Anirudh KhuranaBy Anirudh Khurana16 November 2026Updated:16 November 2026No Comments31 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Support vector machine diagram showing two classes, the decision boundary, dashed margins and ringed support vectors
    Share
    Facebook Twitter LinkedIn Pinterest Email

    A support vector machine (SVM) is a classification algorithm that separates two groups of data with the widest possible gap between them. It was one of the most popular machine learning algorithms before deep learning took over, and it is still a favourite in interviews and in exams, because the idea is simple to draw and the maths behind it is neat.

    This guide explains SVM the way we explain it in our live classes: first the picture, then the code, then the maths. The playground below lets you move sliders, switch kernels, add your own points and watch the model retrain instantly. Spend ten minutes with it before reading the rest, and the sections on C, gamma and kernels will make much more sense.

    You only need basic Python. If you have read our logistic regression guide, some ideas here will feel familiar, but it is not required.

    Free PDF
    SVM notes with code and interview questions
    9 pages, ready to print or read offline. No sign-up needed.
    Download PDF

    What is a support vector machine?

    Imagine a table of students with two columns, hours studied and attendance, and a label saying whether each student passed or failed. Plot them, and the passes sit in one corner and the fails in another. Your job is to draw one line that separates them, so that when a new student comes along you can say which side they fall on.

    The problem is that many lines can separate the two groups. One might pass very close to the failing students, another very close to the passing ones. SVM picks the line that stays as far away as possible from both groups. Think of it as building the widest road between two villages: the middle of the road is the decision boundary, and the two edges of the road are the margin.

    That one choice explains most of SVM. A wide road leaves room for error, so a new student who is slightly unusual still lands on the right side. And the only points that decide where the road goes are the ones standing right at its edges. Those points are called support vectors, which is where the algorithm gets its name.

    SVM playground: see it learn

    Start with the lessons in order. Each one sets up the chart and tells you what to look for. After that, play freely: pick a dataset, switch the kernel, drag the sliders, or click on the chart to add your own points. The model retrains every time you change something.

    Interactive

    SVM playground

    A real SVM trains in your browser every time you change something.

    Guided lessons
    Click on the chart to

    One point per line as x, y, label. Labels can be 0/1 or A/B. Up to 400 points.

    Loading the chart…

    Class AClass BDecision boundaryMargin (edges of the street)Support vector
    Dataset
    Kernel

    The playground scales your data automatically before training, the same way StandardScaler does in scikit-learn, so the sliders behave the same on any data.

    A few things worth trying after the lessons. On the Overlapping dataset, drag C from left to right slowly and count the ringed points. On Moons, set the kernel to RBF and move gamma from low to high; the boundary goes from a near straight line, to a nice curve, to small islands around single points. Then click “Start blank” and draw a pattern of your own.

    Hyperplane, margin and support vectors

    Hyperplane

    The decision boundary of an SVM is called a hyperplane. With two features it is a line, with three features it is a flat plane, and with more features it is the same idea in more dimensions, which we cannot draw but the maths handles easily. Every hyperplane can be written as w · x + b = 0, where w is a vector of weights (one per feature) and b is a bias that shifts the line.

    For any point, the SVM computes the score f(x) = w · x + b. A positive score means one class, a negative score means the other, and the size of the score tells you how far the point is from the boundary. In the playground, hover over the chart to see this score at any spot.

    Margin

    The margin is the empty band around the boundary, between the lines w · x + b = +1 and w · x + b = −1. Its width works out to 2 / ||w||, where ||w|| is the length of the weight vector. So a wider margin means a smaller ||w||, and training an SVM is mostly about making ||w|| as small as possible while keeping the points on the correct side.

    Support vectors

    Support vectors are the training points that lie on the margin, inside it, or on the wrong side of the boundary. They are the only points with a non-zero weight in the final model. You can delete every other training point and retrain, and the boundary will not move. Lesson 2 in the playground lets you check this yourself.

    This is also why SVMs are memory efficient at prediction time: the model only needs to remember the support vectors, not the whole training set.

    TermWhat it meansIn the playground
    HyperplaneThe decision boundary, w · x + b = 0Solid line
    MarginThe empty band around the boundary, width 2 / ||w||Space between the dashed lines
    Support vectorsPoints on or inside the margin, the only ones that shape the modelRinged points
    Score f(x)Signed distance-like value; the sign gives the classHover value; colour strength

    Your first SVM in Python

    Here is the student example from earlier, with 12 students. We train a linear SVM with scikit-learn and then ask it about two new students.

    import numpy as np
    from sklearn.svm import SVC
    
    # Hours studied and attendance (%) for 12 students, and whether they passed (1) or failed (0)
    X = np.array([
        [1, 40], [2, 55], [2, 35], [3, 50], [4, 45], [3, 30],   # failed
        [6, 75], [7, 80], [5, 85], [8, 70], [7, 90], [6, 65],   # passed
    ])
    y = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1])
    
    model = SVC(kernel="linear", C=1.0)
    model.fit(X, y)
    
    print("Weights (w):", model.coef_[0].round(3))
    print("Bias (b):", model.intercept_.round(3))
    print("Support vectors per class:", model.n_support_)
    print("Support vectors:\n", model.support_vectors_)
    
    new_students = np.array([[5, 62], [6, 50]])  # 5 hrs / 62% and 6 hrs / 50%
    print("Predictions:", model.predict(new_students))
    print("Distance score:", model.decision_function(new_students).round(2))

    Output:

    Weights (w): [0.069 0.172]
    Bias (b): [-10.621]
    Support vectors per class: [1 1]
    Support vectors:
     [[ 2. 55.]
     [ 6. 65.]]
    Predictions: [1 0]
    Distance score: [ 0.41 -1.59]

    Out of 12 students, only 2 became support vectors: the failing student with 2 hours and 55% attendance, and the passing student with 6 hours and 65% attendance. They are the two students closest to the border between pass and fail, and the other 10 have no effect on the line.

    The first new student (5 hours, 62%) gets a score of 0.41, so the model predicts pass. Because 0.41 is below 1, that student falls inside the margin, which tells you the model is not very confident. The second student studied 6 hours but has only 50% attendance, and gets a clear fail at −1.59.

    Notice the weights: 0.069 for hours and 0.172 for attendance. That does not mean attendance matters more. Attendance is measured on a scale of 30 to 90 while hours go from 1 to 8, so the weights are on different scales. This is exactly why you should scale features before using SVM, which we will do in the real dataset example later.

    Hard margin vs soft margin, and what C does

    A hard margin SVM insists that every training point is on the correct side, outside the margin. That only works when the classes can be separated perfectly, and even then one strange point can drag the whole boundary towards it. Real data is messy, so in practice we always use a soft margin SVM, which is allowed to let some points sit inside the margin or even on the wrong side, at a cost.

    The parameter C sets that cost. With a small C, mistakes are cheap, so the SVM prefers a wide margin and accepts some errors. With a large C, mistakes are expensive, so it narrows the margin to classify more training points correctly. Here is what that looks like on 300 points from two groups that overlap a little:

    import numpy as np
    from sklearn.datasets import make_blobs
    from sklearn.model_selection import train_test_split
    from sklearn.svm import SVC
    
    # Two groups that overlap a little
    X, y = make_blobs(n_samples=300, centers=2, cluster_std=2.2, random_state=7)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)
    
    for C in [0.01, 1, 100]:
        model = SVC(kernel="linear", C=C).fit(X_train, y_train)
        margin = 2 / np.linalg.norm(model.coef_[0])
        print(f"C={C:<5} support vectors={len(model.support_):<4}"
              f"margin width={margin:.2f}  train acc={model.score(X_train, y_train):.3f}"
              f"  test acc={model.score(X_test, y_test):.3f}")

    Output:

    C=0.01  support vectors=47  margin width=4.39  train acc=0.962  test acc=0.956
    C=1     support vectors=16  margin width=1.33  train acc=0.971  test acc=0.933
    C=100   support vectors=12  margin width=0.86  train acc=0.971  test acc=0.933

    With C = 0.01 the margin is 4.39 units wide and 47 points act as support vectors. At C = 100 the margin shrinks to 0.86 and only 12 points are support vectors. Training accuracy goes up slightly with C, but on this noisy data the test accuracy is actually best with the smallest C (0.956 vs 0.933).

    There is no universally good value for C. The usual approach is to try values like 0.01, 0.1, 1, 10 and 100 with cross-validation and keep the best, which we do with GridSearchCV further down.

    The kernel trick: SVM for curved boundaries

    A linear SVM can only draw straight lines. Look at the Circles dataset in the playground: one class sits inside a ring of the other, and no straight line can separate them. The kernel trick is how SVM handles this.

    The idea is to add new features so that the data becomes separable. The small demo below has points on a single line: blue on the outside, orange in the middle. No single cut point separates them. Drag the slider to add a second feature, x², to every point and watch what happens.

    Interactive

    The kernel trick in one dimension

    Drag the slider to lift each point to the height x².

    Loading the chart…

    In the new 2D space, a flat line separates the classes. Bring that line back down to the original single feature and it becomes two cut points, one on each side of the orange group. A straight boundary in a higher dimension looks curved in the original one.

    Creating these extra features by hand gets expensive quickly. With 100 features, all pairwise products alone are about 5,000 new features. Fortunately, the SVM training maths only needs the dot product between pairs of points. A kernel function computes that dot product as if the points had been mapped to the bigger space, without ever building the new features. That shortcut is the kernel trick.

    KernelFormulaUse it when
    LinearK(a, b) = a · bThe data is roughly separable by a straight line, or you have many features (text, for example)
    PolynomialK(a, b) = (γ a · b + r)dFeature interactions matter; degree 2 or 3 is common
    RBF (Gaussian)K(a, b) = exp(−γ ||a − b||²)You do not know the shape of the boundary; the usual default
    SigmoidK(a, b) = tanh(γ a · b + r)Rarely; it behaves like a small neural network layer

    Here is how the first three kernels do on circular data in scikit-learn:

    from sklearn.datasets import make_circles
    from sklearn.model_selection import train_test_split
    from sklearn.svm import SVC
    
    # One class forms a ring around the other: no straight line can split them
    X, y = make_circles(n_samples=400, factor=0.4, noise=0.08, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    for kernel in ["linear", "poly", "rbf"]:
        model = SVC(kernel=kernel, degree=2, C=1.0).fit(X_train, y_train)
        print(f"{kernel:<7} test accuracy = {model.score(X_test, y_test):.3f}")

    Output:

    linear  test accuracy = 0.408
    poly    test accuracy = 1.000
    rbf     test accuracy = 1.000

    The linear kernel scores 0.408, which is worse than guessing, because a straight line cannot follow a ring. Both the degree 2 polynomial and RBF kernels classify every test point correctly. A degree 2 polynomial works here because a circle is a degree 2 shape (x² + y²).

    What gamma does in an RBF SVM

    The RBF kernel measures how similar two points are by their distance. gamma controls how quickly that similarity drops off. A small gamma means each support vector influences a large area, which gives smooth, simple boundaries. A large gamma means each point only influences its immediate neighbourhood, so the boundary can bend around individual points.

    from sklearn.datasets import make_moons
    from sklearn.model_selection import train_test_split
    from sklearn.svm import SVC
    
    X, y = make_moons(n_samples=400, noise=0.25, random_state=3)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3)
    
    for gamma in [0.1, 1, 10, 100]:
        model = SVC(kernel="rbf", C=1.0, gamma=gamma).fit(X_train, y_train)
        print(f"gamma={gamma:<5} train acc={model.score(X_train, y_train):.3f}"
              f"  test acc={model.score(X_test, y_test):.3f}  support vectors={len(model.support_)}")

    Output:

    gamma=0.1   train acc=0.882  test acc=0.867  support vectors=115
    gamma=1     train acc=0.932  test acc=0.925  support vectors=73
    gamma=10    train acc=0.961  test acc=0.908  support vectors=102
    gamma=100   train acc=0.993  test acc=0.892  support vectors=244

    As gamma goes from 0.1 to 100, training accuracy climbs from 0.882 to 0.993. Test accuracy tells a different story: it peaks at gamma = 1 (0.925) and falls after that. At gamma = 100, 244 of the 280 training points are support vectors, which is the model memorising the data. Lesson 7 in the playground shows this visually.

    C and gamma work together. A high gamma with a high C is the easiest way to overfit, and a low gamma with a low C can underfit. Tune them as a pair.

    The maths behind SVM, in plain words

    You do not need the maths to use SVM, but interviewers like to ask about it, and it explains why the algorithm behaves the way it does. Labels are written as y = +1 or y = −1.

    The hard margin problem

    We want the widest margin, which means the smallest ||w||, while every point is on the correct side and outside the margin:

    minimise ½ ||w||²   such that   yi (w · xi + b) ≥ 1 for every point i

    Squaring ||w|| and halving it makes the maths easier and does not change the answer.

    The soft margin problem and hinge loss

    To allow mistakes, each point gets some slack, and C sets the price of that slack. Written as a single loss to minimise, this becomes:

    ½ ||w||² + C × Σ max(0, 1 − yi (w · xi + b))

    The second part is the hinge loss. A point safely outside the margin (score times label at least 1) costs nothing. A point inside the margin costs a little, and a point on the wrong side costs more the further it is. Compare this with logistic regression, where every point adds some loss, even the easy ones. That difference is why only the support vectors end up mattering in SVM.

    The dual problem, where kernels come in

    Using Lagrange multipliers, the same problem can be rewritten in its dual form, with one weight αi per training point, each between 0 and C:

    maximise Σ αi − ½ Σ Σ αi αj yi yj K(xi, xj)   with Σ αi yi = 0

    After training, most α values are exactly 0. The points with α greater than 0 are the support vectors, and a new point is classified with f(x) = Σ αi yi K(xi, x) + b. The data only appears inside the kernel function K, which is why any valid kernel can be swapped in. scikit-learn solves this dual with an algorithm called SMO (sequential minimal optimisation), and the playground on this page runs the same method in your browser.

    SVM from scratch with NumPy

    Writing a linear SVM yourself is the best way to make the hinge loss click. The version below uses plain gradient descent on the soft margin loss from the previous section. For points outside the margin the gradient only shrinks w; for points inside it, the gradient also pulls the boundary towards classifying them correctly.

    import numpy as np
    from sklearn.datasets import make_blobs
    
    class LinearSVM:
        """Soft-margin linear SVM trained with gradient descent on the hinge loss."""
    
        def __init__(self, C=1.0, lr=0.0001, epochs=2000):
            self.C, self.lr, self.epochs = C, lr, epochs
    
        def fit(self, X, y):
            y = np.where(y <= 0, -1, 1)          # SVM needs labels -1 and +1
            n, d = X.shape
            self.w, self.b = np.zeros(d), 0.0
            for epoch in range(self.epochs):
                margins = y * (X @ self.w + self.b)
                wrong = margins < 1               # points inside the margin or misclassified
                # gradient of 0.5*||w||^2 + C * sum(max(0, 1 - y(w.x + b)))
                grad_w = self.w - self.C * (y[wrong] @ X[wrong])
                grad_b = -self.C * y[wrong].sum()
                self.w -= self.lr * grad_w
                self.b -= self.lr * grad_b
                if epoch % 500 == 0:
                    hinge = np.maximum(0, 1 - margins).sum()
                    loss = 0.5 * self.w @ self.w + self.C * hinge
                    print(f"epoch {epoch:<4} loss={loss:.2f}")
            return self
    
        def predict(self, X):
            return np.where(X @ self.w + self.b >= 0, 1, 0)
    
    X, y = make_blobs(n_samples=200, centers=2, cluster_std=1.2, random_state=4)
    svm = LinearSVM(C=1.0).fit(X, y)
    print("w =", svm.w.round(3), " b =", round(svm.b, 3))
    print("training accuracy =", (svm.predict(X) == y).mean())
    print("margin width =", round(2 / np.linalg.norm(svm.w), 3))
    
    # Compare with scikit-learn on the same data
    from sklearn.svm import SVC
    print("scikit-learn accuracy =", SVC(kernel="linear", C=1.0).fit(X, y).score(X, y))

    Output:

    epoch 0    loss=200.00
    epoch 500  loss=36.68
    epoch 1000 loss=35.82
    epoch 1500 loss=35.40
    w = [-0.318  1.408]  b = -0.634
    training accuracy = 0.94
    margin width = 1.386
    scikit-learn accuracy = 0.935

    The loss starts at 200 (every one of the 200 points is inside the margin when w is zero) and settles around 35. This 23-line class reaches 94% training accuracy, slightly above scikit-learn’s 93.5% on the same data. The two do not match exactly because gradient descent with a fixed learning rate only gets close to the best solution, while scikit-learn solves the problem exactly. For real projects, use scikit-learn; it is faster, exact and supports kernels.

    SVM on a real dataset: breast cancer classification

    The breast cancer dataset that ships with scikit-learn has 569 tumours, each described by 30 measurements, labelled as malignant or benign. Some features are in the thousands (area) and others are below 1 (smoothness), which makes it a good test of why scaling matters.

    from sklearn.datasets import load_breast_cancer
    from sklearn.model_selection import train_test_split, GridSearchCV
    from sklearn.pipeline import make_pipeline
    from sklearn.preprocessing import StandardScaler
    from sklearn.svm import SVC
    
    X, y = load_breast_cancer(return_X_y=True)          # 569 tumours, 30 features each
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.25, random_state=42, stratify=y)
    
    # 1) Without scaling
    raw = SVC(kernel="rbf").fit(X_train, y_train)
    print("Without scaling:", round(raw.score(X_test, y_test), 3))
    
    # 2) With scaling + a small grid search over C and gamma
    pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
    grid = GridSearchCV(pipe, {"svc__C": [0.1, 1, 10, 100],
                               "svc__gamma": ["scale", 0.01, 0.1, 1]}, cv=5)
    grid.fit(X_train, y_train)
    print("Best settings:", grid.best_params_)
    print("With scaling + tuning:", round(grid.score(X_test, y_test), 3))

    Output:

    Without scaling: 0.923
    Best settings: {'svc__C': 1, 'svc__gamma': 0.01}
    With scaling + tuning: 0.972

    Without scaling, the RBF SVM gets 92.3% test accuracy. Putting a StandardScaler in front of it and searching over C and gamma with 5-fold cross-validation brings that to 97.2%. The best settings were C = 1 and gamma = 0.01.

    Two habits from this example are worth keeping. Always put the scaler and the SVM in one Pipeline, so the scaler only learns from the training folds during cross-validation. And always tune C and gamma together rather than one at a time. To understand the accuracy number properly, look at the confusion matrix too; our interactive confusion matrix guide explains how.

    Multiclass SVM: more than two classes

    An SVM separates two classes at a time, so for three or more classes it combines several binary SVMs. There are two common ways:

    • One-vs-one (OvO): train one SVM for every pair of classes, then let them vote. With 3 classes that is 3 SVMs, and with 10 classes it is 45. scikit-learn’s SVC uses this.
    • One-vs-rest (OvR): train one SVM per class, each separating that class from all the others, and pick the class with the highest score. LinearSVC uses this.

    You do not have to do anything special in code. Pass in a multiclass target and scikit-learn handles it:

    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    from sklearn.svm import SVC
    
    X, y = load_iris(return_X_y=True)                    # 3 flower species
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
    
    model = SVC(kernel="rbf", C=1.0).fit(X_train, y_train)
    print("Classes:", model.classes_)
    print("Test accuracy:", round(model.score(X_test, y_test), 3))
    print("Predicted species for first 5 test flowers:", model.predict(X_test[:5]))
    print("Actual species:                            ", y_test[:5])

    Output:

    Classes: [0 1 2]
    Test accuracy: 0.978
    Predicted species for first 5 test flowers: [2 1 0 2 0]
    Actual species:                             [2 1 0 2 0]

    On the iris dataset, with 3 flower species, the RBF SVM gets 97.8% of the test flowers right.

    Can SVM do regression? Meet SVR

    Yes. Support vector regression (SVR) flips the idea around. Instead of keeping points outside a margin, it fits a tube of width epsilon around the predicted line and tries to keep as many points as possible inside the tube. Points inside the tube cost nothing, and only the points outside it become support vectors. In scikit-learn it is from sklearn.svm import SVR, with the same kernels, C and gamma, plus an epsilon parameter for the tube width. For most regression problems, though, you will start with linear regression or tree-based models.

    How to choose the kernel, C and gamma

    1. Scale your features first with StandardScaler, inside a pipeline.
    2. Start with a linear kernel if you have many features compared with rows (for example, text data with thousands of words). It is fast and often just as good.
    3. Otherwise, start with the RBF kernel and gamma="scale", the scikit-learn default.
    4. Search C over 0.01 to 100 and gamma over 0.001 to 10 on a log scale with GridSearchCV.
    5. If training accuracy is much higher than validation accuracy, lower gamma or C. If both are low, raise them or try a different kernel.
    6. For imbalanced classes, set class_weight="balanced".
    7. If you need probabilities, set probability=True, but know that it adds an extra internal cross-validation and slows training down.

    SVM vs logistic regression

    Both draw a boundary between classes, and with a linear kernel they often give similar results. The differences show up in what they optimise and what they give you back.

    SVMLogistic regression
    GoalWidest margin between classesBest probability estimates
    LossHinge loss (easy points cost nothing)Log loss (every point counts)
    OutputA class and a distance scoreA probability between 0 and 1
    Curved boundariesYes, through kernelsOnly with manually added features
    Large datasetsKernel SVM gets slow beyond tens of thousands of rowsScales well to millions of rows
    OutliersLess affected, since only support vectors matterMore affected
    InterpretabilityHarder with kernelsEasy: each weight changes the log-odds

    A practical rule: if you need probabilities or an easy explanation, use logistic regression. If you have a medium-sized dataset with a curved boundary, try an RBF SVM.

    Advantages and limitations of SVM

    Where SVM does well

    • Works well in high dimensions, even when there are more features than rows.
    • Only the support vectors are stored, so prediction uses little memory.
    • Kernels let it learn complex boundaries without manual feature engineering.
    • The training problem is convex, so it always finds the same best solution.

    Where SVM struggles

    • Kernel SVM training time grows quickly with the number of rows, roughly between n² and n³, so it is slow on hundreds of thousands of rows.
    • Results depend heavily on feature scaling and on choosing C and gamma.
    • It does not give probabilities directly.
    • With many overlapping classes and lots of noise, other models (gradient boosting, for example) usually do better.

    SVM interview questions and answers

    These are the SVM questions that come up most in data science and machine learning interviews, with short answers you can say out loud.

    1. What is a support vector machine?

    A supervised learning algorithm, used mainly for classification, that finds the hyperplane separating two classes with the largest possible margin. It can also do regression (SVR) and handle curved boundaries using kernels.

    2. What are support vectors?

    The training points that lie on the margin, inside it, or on the wrong side of the boundary. They have non-zero Lagrange multipliers and are the only points that determine the decision boundary.

    3. Why does SVM maximise the margin?

    A wider margin leaves more room for new points that differ slightly from the training data, so the model tends to generalise better. In learning theory, a larger margin corresponds to lower model complexity.

    4. What is the difference between a hard margin and a soft margin SVM?

    A hard margin SVM allows no point inside the margin or on the wrong side, so it only works on perfectly separable data and is very sensitive to outliers. A soft margin SVM adds slack variables so some points can break the margin, at a cost controlled by C.

    5. What does the C parameter do?

    C is the penalty for points that violate the margin. A small C gives a wider, more forgiving margin and more support vectors. A large C gives a narrower margin that tries to classify every training point correctly, which can overfit noisy data.

    6. What is the kernel trick?

    A way to compute the dot product of two points as if they had been mapped to a higher-dimensional feature space, without computing that mapping. Since the SVM dual only uses dot products, this lets it learn non-linear boundaries cheaply.

    7. Which kernels are commonly used?

    Linear, polynomial, RBF (Gaussian) and sigmoid. RBF is the usual default when you do not know the shape of the data, and linear is preferred for high-dimensional data such as text.

    8. What does gamma do in the RBF kernel?

    It controls how far the influence of a single training point reaches. Low gamma gives smooth, wide-reaching influence and simple boundaries. High gamma gives very local influence and wiggly boundaries that can overfit.

    9. Why is feature scaling important for SVM?

    The RBF kernel uses distances and the linear kernel uses dot products. A feature with a large range, like salary in rupees, would dominate a feature with a small range, like age, unless both are scaled.

    10. What is hinge loss?

    The loss max(0, 1 − y·f(x)). It is zero when a point is on the correct side and outside the margin, and grows linearly as the point moves into the margin or across the boundary.

    11. What is the difference between the primal and the dual form?

    The primal form optimises the weights w and bias b directly. The dual form optimises one multiplier α per training point and only uses the data through dot products, which is what makes kernels possible. Kernel SVMs are trained in the dual.

    12. What makes a function a valid kernel?

    It must correspond to a dot product in some feature space. Mercer’s condition says the kernel matrix it produces for any set of points must be symmetric and positive semi-definite.

    13. How does SVM handle multiclass problems?

    By combining binary SVMs. One-vs-one trains a classifier for every pair of classes and takes a vote; one-vs-rest trains one classifier per class against all others. scikit-learn’s SVC uses one-vs-one.

    14. Can SVM output probabilities?

    Not directly. scikit-learn can estimate them with Platt scaling when you set probability=True, which fits a logistic model on the SVM scores using internal cross-validation. It makes training slower.

    15. How do you handle imbalanced data with SVM?

    Give the minority class a higher penalty using class_weight=”balanced” (or custom weights), so mistakes on it cost more. Resampling the data and choosing a better metric than accuracy also help.

    16. What is the time complexity of training an SVM?

    Kernel SVM training is roughly between O(n²) and O(n³) in the number of training rows, and storing the kernel matrix takes O(n²) memory. Linear SVMs trained with LinearSVC or SGD scale roughly linearly.

    17. When would you not use an SVM?

    On very large datasets, when you need well-calibrated probabilities, when the model must be easy to explain, or on noisy data with heavily overlapping classes where ensembles usually do better.

    18. What is the difference between SVM and logistic regression?

    SVM maximises the margin using hinge loss and only depends on the support vectors. Logistic regression maximises likelihood using log loss, every point contributes, and it outputs probabilities directly.

    Test yourself: SVM quiz

    Ten questions on everything above. If you get eight or more right, you are ready for SVM questions in an interview.

    Quiz

    Support vector machine quiz

    10 questions, about three minutes.

    Download the free SVM notes (PDF)

    Everything on this page in a printable format: the main ideas, the C and gamma cheat sheet, all seven code examples with their outputs, and the interview questions. Handy for revising before an exam or an interview.

    Free PDF

    SVM notes by Code and Debug

    9 pages, no sign-up needed.

    Download PDF

    Frequently asked questions

    Is SVM supervised or unsupervised learning?

    SVM is supervised learning. It needs labelled training data to learn the boundary. A related method, one-class SVM, can be used without labels for outlier detection.

    Is SVM used for classification or regression?

    Mostly classification, but it can do both. Support vector classification (SVC) separates classes with a margin, and support vector regression (SVR) fits a tube around a line to predict numbers.

    Which SVM kernel is best?

    There is no single best kernel. Use a linear kernel when the data is high dimensional or roughly linearly separable, and the RBF kernel as a default for everything else. Compare them with cross-validation.

    What are C and gamma in SVM?

    C controls how much the SVM penalises training points that fall inside the margin or on the wrong side. Gamma, used by the RBF and polynomial kernels, controls how far each training point’s influence reaches. Both are tuned together with grid search.

    Is SVM better than logistic regression?

    Neither is better in general. SVM handles curved boundaries through kernels and is less affected by outliers. Logistic regression gives probabilities, is easier to interpret and scales to much larger datasets.

    Is SVM still used today?

    Yes. It is still a strong choice for small and medium tabular datasets, text classification and problems with many features, and it is a common topic in machine learning interviews. Deep learning has replaced it mainly for images, audio and very large datasets.

    What to learn next

    • Logistic regression in machine learning, the other classic linear classifier, with its own interactive visuals.
    • Confusion matrix in machine learning, to judge your SVM beyond plain accuracy.
    • Linear regression in machine learning, if you want the basics of how models learn from data.
    • How to learn AI and ML from scratch, our full roadmap with a personal study planner.
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous Article100 OOPs Interview Questions and Answers (Freshers to Experienced)
    Next Article Decision Tree in Machine Learning: An Interactive Guide (with Python)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    AI & Machine Learning

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026
    AI & Machine Learning

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026
    AI & Machine Learning

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (7)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (5)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026

    100 OOPs Interview Questions and Answers (Freshers to Experienced)

    16 November 2026

    100 Computer Networks Interview Questions and Answers (Freshers to Experienced)

    15 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.