|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +SEED = 1234 |
| 4 | + |
| 5 | +## ANCHOR: load_data_from_csv |
| 6 | +import numpy as np |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import pandas as pd |
| 9 | + |
| 10 | +path_to_csv = "aptamer_classification_data.csv" |
| 11 | +df = pd.read_csv(path_to_csv) |
| 12 | +print(df.head()) |
| 13 | +### ANCHOR_END: load_data_from_csv |
| 14 | + |
| 15 | +### ANCHOR: process_data |
| 16 | +target_column = "lambda_abs_class" |
| 17 | + |
| 18 | +X = df[["PC1", "PC2"]].values # Select the PC1 and PC2 columns as features |
| 19 | +X = np.hstack([X, np.ones((X.shape[0], 1))]) # Add a column of ones to the data matrix |
| 20 | +y = df[target_column].values # Target column |
| 21 | + |
| 22 | +print(X.shape) |
| 23 | +print(y.shape) |
| 24 | +### ANCHOR_END: process_data |
| 25 | + |
| 26 | +# fig.savefig('../../assets/figures/05-machine_learning/classification_data.svg') |
| 27 | + |
| 28 | +### ANCHOR: svm_init |
| 29 | +class SupportVectorMachine: |
| 30 | + def __init__(self, learning_rate=0.01, n_iterations=50, lam=10.0): |
| 31 | + self.learning_rate = learning_rate |
| 32 | + self.n_iterations = n_iterations |
| 33 | + self.lam = lam # regularization parameter lambda |
| 34 | + self.weights = None |
| 35 | + self.losses = [] # store loss values for each epoch |
| 36 | + self.margins = [] # store margin values (2 / ||w||) for each epoch |
| 37 | +### ANCHOR_END: svm_init |
| 38 | + |
| 39 | +### ANCHOR: svm_fit |
| 40 | + def fit(self, X, y): |
| 41 | + n_samples, n_features = X.shape |
| 42 | + self.weights = np.random.randn(n_features) |
| 43 | + |
| 44 | + for epoch in range(self.n_iterations): |
| 45 | + epoch_loss = 0 |
| 46 | + |
| 47 | + for i, (x_i, y_i) in enumerate(zip(X, y)): |
| 48 | + # Calculate prediction |
| 49 | + prediction = np.dot(x_i, self.weights) |
| 50 | + |
| 51 | + # Calculate hinge loss for this sample |
| 52 | + hinge_loss = max(0, 1 - y_i * prediction) |
| 53 | + |
| 54 | + # Update weights based on whether point is misclassified |
| 55 | + if y_i * prediction < 1: # misclassified or within margin |
| 56 | + # Gradient of hinge loss + regularization |
| 57 | + self.weights = (1 - self.learning_rate * self.lam) * self.weights + self.learning_rate * y_i * x_i |
| 58 | + else: # correctly classified |
| 59 | + # Only regularization term |
| 60 | + self.weights = (1 - self.learning_rate * self.lam) * self.weights |
| 61 | + |
| 62 | + # Accumulate loss for this epoch |
| 63 | + epoch_loss += hinge_loss |
| 64 | + |
| 65 | + # Calculate total loss for this epoch (hinge loss + regularization) |
| 66 | + regularization_loss = 0.5 * self.lam * np.dot(self.weights, self.weights) |
| 67 | + total_loss = epoch_loss / n_samples + regularization_loss |
| 68 | + self.losses.append(total_loss) |
| 69 | + |
| 70 | + # Calculate margin (2 / ||w||) |
| 71 | + weight_norm = np.linalg.norm(self.weights) |
| 72 | + margin = 2 / weight_norm if weight_norm > 0 else 0 |
| 73 | + self.margins.append(margin) |
| 74 | + |
| 75 | + if epoch % 10 == 0: |
| 76 | + print(f"Epoch {epoch}, Loss: {total_loss:.4f}, Margin: {margin:.4f}") |
| 77 | +### ANCHOR_END: svm_fit |
| 78 | + |
| 79 | +### ANCHOR: svm_predict |
| 80 | + def predict(self, X): |
| 81 | + return np.sign(np.dot(X, self.weights)) |
| 82 | +### ANCHOR_END: svm_predict |
| 83 | + |
| 84 | +np.random.seed(SEED) |
| 85 | +### ANCHOR: fit_svm_model |
| 86 | +svm_model = SupportVectorMachine(learning_rate=0.01, n_iterations=100, lam=0.1) |
| 87 | +svm_model.fit(X, y) |
| 88 | +y_pred_svm = svm_model.predict(X) |
| 89 | +### ANCHOR_END: fit_svm_model |
| 90 | + |
| 91 | +### ANCHOR: calculate_svm_accuracy |
| 92 | +accuracy_svm = np.mean(y_pred_svm == y) |
| 93 | +print(f"SVM Accuracy: {accuracy_svm}") |
| 94 | +### ANCHOR_END: calculate_svm_accuracy |
| 95 | + |
| 96 | +### ANCHOR: plot_svm_decision_boundary |
| 97 | +fig, ax = plt.subplots(figsize=(7, 6)) |
| 98 | + |
| 99 | +# Plot decision boundary |
| 100 | +ax.scatter(X[:, 0], X[:, 1], c=y, cmap='coolwarm', alpha=0.7) |
| 101 | + |
| 102 | +# Define the decision boundary as a function of the first feature |
| 103 | +x1_range = np.linspace(X[:, 0].min(), X[:, 0].max(), 100) |
| 104 | +if svm_model.weights[1] != 0: |
| 105 | + x2_boundary = -(svm_model.weights[0] * x1_range + svm_model.weights[2]) / svm_model.weights[1] |
| 106 | + ax.plot(x1_range, x2_boundary, 'k--', linewidth=2, label='SVM Decision Boundary') |
| 107 | + |
| 108 | +ax.legend(loc='upper right') |
| 109 | +ax.set_xlabel('PC1') |
| 110 | +ax.set_ylabel('PC2') |
| 111 | +ax.set_title('SVM Decision Boundary') |
| 112 | +ax.set_xlim(X[:, 0].min()-0.1, X[:, 0].max()+0.1) |
| 113 | +ax.set_ylim(X[:, 1].min()-0.1, X[:, 1].max()+0.1) |
| 114 | + |
| 115 | +plt.show() |
| 116 | +### ANCHOR_END: plot_svm_decision_boundary |
| 117 | + |
| 118 | + |
0 commit comments