import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC, SVR
X_cls = np.array([[2,3],[3,3],[2,2],[7,8],[8,8],[7,7]])
y_cls = np.array([1,1,1,-1,-1,-1])
plt.figure(figsize=(6,5))
plt.scatter(X_cls[y_cls==1,0], X_cls[y_cls==1,1], color='red', label='Class 1')
plt.scatter(X_cls[y_cls==-1,0], X_cls[y_cls==-1,1], color='blue', label='Class -1')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Raw Data (SVM Classification)')
plt.legend()
plt.show()
clf = SVC(kernel='linear', C=100)
clf.fit(X_cls, y_cls)
w = clf.coef_[0]
b = clf.intercept_[0]
xx = np.linspace(1, 9, 100)
yy = -(w[0]*xx + b)/w[1]
plt.figure(figsize=(6,5))
plt.scatter(X_cls[y_cls==1,0], X_cls[y_cls==1,1], color='red', label='Class 1')
plt.scatter(X_cls[y_cls==-1,0], X_cls[y_cls==-1,1], color='blue', label='Class -1')
plt.plot(xx, yy, 'k-', label='Decision Boundary')
plt.scatter(clf.support_vectors_[:,0], clf.support_vectors_[:,1], s=120, facecolors='none', edgecolors='k', linewidths=1.5, label='Support Vectors')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('SVM Decision Boundary & Support Vectors')
plt.legend()
plt.show()
X_reg = np.array([[-2],[-1],[0],[1],[2]])
y_reg = np.array([-1.1, -0.8, 0.1, 0.9, 1.2])
plt.scatter(X_reg, y_reg, color='blue', label='Data')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Raw Data (SVR Regression)')
plt.legend()
plt.show()
svr = SVR(kernel='linear', C=10, epsilon=0.1)
svr.fit(X_reg, y_reg)
X_plot = np.linspace(-2.5, 2.5, 100).reshape(-1,1)
y_pred = svr.predict(X_plot)
plt.scatter(X_reg, y_reg, color='blue', label='Data')
plt.plot(X_plot, y_pred, color='red', label='SVR Prediction')
plt.xlabel('x')
plt.ylabel('y')
plt.title('SVR Regression with Epsilon-Tube')
plt.plot(X_plot, y_pred + svr.epsilon, 'k--', lw=1)
plt.plot(X_plot, y_pred - svr.epsilon, 'k--', lw=1)
plt.legend()
plt.show()