(a) Here is an example dataset DS2:
import numpy as np
rng = np.random.RandomState(0)
X = np.zeros((100, 3))
X[:50, 0] = rng.randn(50) * 0.5 - 1
X[50:, 0] = rng.randn(50) * 0.5 + 1
X[:50, 1] = rng.randn(50) * 0.5 - 1
X[50:, 1] = rng.randn(50) * 0.5 + 1
X[:25, 2] = 1
X[75:, 2] = 1
np.random.shuffle(X)
y = X[:, 2]
X = X[:, :2]
In this dataset, we have two features and two classes, and the classes are not linearly separable.
To evaluate the performance of the SVM, we will use a stratified 5-fold cross-validation. This means that the data is split into 5 folds, where each fold has roughly the same proportion of each class.
Here is how you can train an SVM with a linear kernel on the full dataset and plot the decision boundary:
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score
clf = SVC(kernel='linear', C=1)
clf.fit(X, y)
xmin, xmax = X[:, 0].min(), X[:, 0].max()
ymin, ymax = X[:, 1].min(), X[:, 1].max()
xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, np.sign(Z), alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='viridis')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Linear SVM with C=1')
plt.show()
skf = StratifiedKFold(n_splits=5)
train_accuracy = []
test_accuracy = []
for train_idx, test_idx in skf.split(X, y):
clf = SVC(kernel='linear', C=1)
clf.fit(X[train_idx], y[train_idx])
y_pred_train = clf.predict(X[train_idx])
y_true_train = y[train_idx]
train_accuracy.append(accuracy_score(y_true_train, y_pred_train))
y_pred_test = clf.predict(X[test_idx])
y_true_test = y[test_idx]
test_accuracy.append(accuracy_score(y_true_test, y_pred_test))
print('Train accuracy: %.2f' % np.mean(train_accuracy))
print('Test accuracy: %.2f' % np.mean(test_accuracy))
Note that we used StratifiedKFold instead of LeaveOneOut cross-validation because LeaveOneOut can be computationally expensive, especially for larger datasets. StratifiedKFold ensures that the split is stratified and has roughly the same proportion of each class in each fold.
(b) Here is how you can use the RBF kernel to improve the SVM:
clf = SVC(kernel='rbf', gamma=1, C=10)
clf.fit(X, y)
xmin, xmax = X[:, 0].min(), X[:, 0].max()
ymin, ymax = X[:, 1].min(), X[:, 1].max()
xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, np.sign(Z), alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='viridis')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('RBF SVM with C=10, gamma=1')
plt.show()
skf = StratifiedKFold(n_splits=5)
train_accuracy = []
test_accuracy = []
for train_idx, test_idx in skf.split(X, y):
clf = SVC(kernel='rbf', gamma=1, C=10)
clf.fit(X[train_idx], y[train_idx])
y_pred_train = clf.predict(X[train_idx])
y_true_train = y[train_idx]
train_accuracy.append(accuracy_score(y_true_train, y_pred_train))
y_pred_test = clf.predict(X[test_idx])
y_true_test = y[test_idx]
test_accuracy.append(accuracy_score(y_true_test, y_pred_test))
print('Train accuracy: %.2f' % np.mean(train_accuracy))
print('Test accuracy: %.2f' % np.mean(test_accuracy))
Note that we used the RBF kernel, which is a popular choice for non-linearly separable datasets, as it can map the data into a higher-dimensional space where it may be easier to separate the classes. We also tuned the hyperparameters C and gamma, which control the tradeoff between margin and error and the width of the RBF kernel, respectively. The resulting decision boundary is non-linear and better separates the classes compared to the linear kernel.
(c) We chose the RBF kernel because it is a powerful and flexible kernel that can model non-linear relationships and is widely used in practice. The kernel works by transforming the data into a high-dimensional feature space defined by the kernel function and using a linear SVM to find the optimal hyperplane that separates the classes with the maximum margin. The hyperparameter gamma controls the width of the RBF kernel and affects the smoothness of the decision boundary. A high value of gamma makes the kernel narrower and the decision boundary more complex, while a low value of gamma makes the kernel wider and the decision boundary smoother. The hyperparmeter C controls the tradeoff between margin and error, and determines how much importance should be given to correctly classifying the training data versus maximizing the margin. By tuning the hyperparameters C and gamma appropriately, we can improve the performance of the SVM and obtain better generalization.