Toto je statické zobrazenie, ak chcete Notebook spustiť, prihláste sa do prostredia Data Lab.
Support Vector Machine (SVM) - Student Assignment¶
Total Points: 8 (4 parts × 2 points each)
Prehľad základných krokov lineárneho SVM¶
1. Zvoliť hyperrovinu: w · x + b = 0
2. Pre každý bod vypočítať rozhodovaciu hodnotu: f(x) = w · x + b
3. Podľa znamienka určiť triedu:
- f(x) >= 0 -> +1
- f(x) < 0 -> -1
4. Hľadať hyperrovinu s čo najväčším marginom
V tomto cvičení sa zameriame na lineárny SVM pre binárnu klasifikáciu s triedami -1 a 1.
Z článku na GeeksforGeeks si zapamätajte hlavné pojmy:
- Hyperplane: rozhodovacia hranica medzi triedami
- Support vectors: body najbližšie k hyperrovine
- Margin: vzdialenosť medzi triedami a rozhodovacou hranicou
- Kernel: funkcia podobnosti; v tomto zadaní použijeme linear kernel
Setup - Required Imports¶
In [ ]:
import numpy as np
Part 1: Linear Kernel (2 points)¶
Implementujte lineárny kernel, ktorý pre dva vektory vypočíta ich skalárny súčin.
Vzorec: $K(x_1, x_2) = x_1 \cdot x_2 = \sum_{i=1}^{n} x_{1,i} x_{2,i}$
Vstupy:
x1: prvý vektorx2: druhý vektor
Výstup:
result: skalárny súčin vektorovx1ax2
In [ ]:
def linear_kernel(x1: np.ndarray, x2: np.ndarray) -> float:
# Sample return value for [1, 2] and [3, 4]: 11.0
"""
Compute the linear kernel (dot product) of two vectors.
Args:
x1: First vector
x2: Second vector
Returns:
result: float - Dot product of x1 and x2
"""
result = 0.0
# TODO: Implement linear kernel
# Your code here
return result
Part 2: Decision Function (2 points)¶
Implementujte rozhodovaciu funkciu lineárneho SVM.
Vzorec: $f(X) = X \cdot w + b$
Premenné:
X: matica vstupných bodovw: vektor váh hyperrovinyb: bias
Vstupy:
X: 2D numpy pole tvaru(počet_bodov, počet_atribútov)w: 1D numpy pole váhb: číslo typufloat
Výstup:
scores: 1D pole rozhodovacích hodnôt pre každý bod
In [ ]:
def decision_function(X: np.ndarray, w: np.ndarray, b: float) -> np.ndarray:
# Sample return value for X=[[1,2],[3,1]], w=[2,-1], b=-0.5: array([-0.5, 4.5])
"""
Compute the linear SVM decision scores.
Args:
X: Feature matrix of shape (m, n)
w: Weight vector of shape (n,)
b: Bias term
Returns:
scores: np.ndarray - Decision values for each input row
"""
scores = np.zeros(X.shape[0], dtype=float)
# TODO: Implement decision function
# Your code here
return scores
Part 3: Predict the Class (2 points)¶
Implementujte finálnu predikciu triedy podľa znamienka rozhodovacej funkcie.
Pravidlo klasifikácie:
- ak
score >= 0, výsledná trieda je1 - ak
score < 0, výsledná trieda je-1
Vstupy:
X: vstupné bodyw: váhyb: bias
Výstup:
predictions: pole tried-1alebo1
In [ ]:
def svm_predict(X: np.ndarray, w: np.ndarray, b: float) -> np.ndarray:
# Sample return value for scores [-0.5, 4.5]: array([-1, 1])
"""
Predict SVM classes using the sign of the decision function.
Args:
X: Feature matrix
w: Weight vector
b: Bias term
Returns:
predictions: np.ndarray - Predicted labels (-1 or 1)
"""
predictions = np.zeros(X.shape[0], dtype=int)
# TODO: Implement SVM prediction
# Your code here
return predictions
Part 4: Margin Width (2 points)¶
Implementujte výpočet šírky marginu pre lineárny SVM.
Vzorec: $\text{margin} = \frac{2}{||w||}$
kde $||w|| = \sqrt{w_1^2 + w_2^2 + ... + w_n^2}$
Vstup:
w: vektor váh hyperroviny
Výstup:
margin: šírka marginu akofloat
In [ ]:
def margin_width(w: np.ndarray) -> float:
# Sample return value for w=[3,4]: 0.4
"""
Compute the margin width of a linear SVM hyperplane.
Args:
w: Weight vector
Returns:
margin: float - Width of the margin
"""
margin = 0.0
# TODO: Implement margin width
# Your code here
return margin
Testing Dataset¶
In [ ]:
x1 = np.array([1.0, 2.0])
x2 = np.array([3.0, 4.0])
X_test = np.array([
[1.0, 2.0],
[3.0, 1.0],
[-1.0, -2.0],
[0.0, 1.0]
])
w_test = np.array([2.0, -1.0])
b_test = -0.5
w_margin = np.array([3.0, 4.0])
Test your implementation¶
In [ ]:
kernel_result = linear_kernel(x1, x2)
print("Part 1 - Linear Kernel:")
print(f"Input vectors: {x1}, {x2}")
print(f"Your result: {kernel_result}")
print("Expected: 11.0")
print()
In [ ]:
decision_result = decision_function(X_test, w_test, b_test)
print("Part 2 - Decision Function:")
print(f"Your result: {decision_result}")
print("Expected: [-0.5 4.5 -0.5 -1.5]")
print()
In [ ]:
prediction_result = svm_predict(X_test, w_test, b_test)
print("Part 3 - SVM Prediction:")
print(f"Your result: {prediction_result}")
print("Expected: [-1 1 -1 -1]")
print()
In [ ]:
margin_result = margin_width(w_margin)
print("Part 4 - Margin Width:")
print(f"Your result: {margin_result}")
print("Expected: 0.4")
print()