Experiment 4
Experiment 4
# Load dataset
iris = datasets.load_iris()
X = iris.data[:, :2] # Take only the first two features for 2D
visualization
y = iris.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=42)
# Kernel options
kernels = ['linear', 'poly', 'rbf']
# Plotting function
def plot_decision_boundary(clf, X, y, title):
h = .02 # step size in the mesh
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(6, 4))
plt.contourf(xx, yy, Z, alpha=0.3)
plt.scatter(X[:, 0], X[:, 1], c=y, s=30, edgecolors='k')
plt.title(f"SVM with {title} kernel")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
clf.fit(X_train, y_train)
plot_decision_boundary(clf, X, y, kernel)