← back

Linear Kernel Function

#45 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement a linear kernel function for support vector machines. The linear kernel computes the dot product between two input vectors.

Solution

1
2
3
4
5
6
import numpy as np

def linear_kernel(x1, x2):
    x1 = np.array(x1, dtype=np.float64)
    x2 = np.array(x2, dtype=np.float64)
    return float(np.dot(x1, x2))

Explanation

  1. Convert both inputs to NumPy arrays.
  2. Compute the dot product using np.dot.
  3. The linear kernel K(x1, x2) = x1 . x2 measures similarity as the inner product in the original feature space.
  4. It is used when data is linearly separable or as a baseline kernel.

Complexity

  • Time: O(d) where d is the dimensionality of the vectors
  • Space: O(1) for the scalar result