A class implementing Support Vector Machine with automatic differentiation.
A class implementing Support Vector Machine with automatic differentiationThis class provides functionality for binary classification using Support Vector Machines with automatic gradient computation similar to PyTorch's autograd engine.
- Template Parameters
-
T | The data type for matrix elements (typically float or double) |
SVM<double> svm(KernelType::RBF, 1.0, 0.1);
Matrix<double> X_train = training_features;
std::vector<int> y_train = training_labels;
svm.fit(X_train, y_train);
Matrix<double> X_test = test_features;
std::vector<int> predictions = svm.predict(X_test);
#pragma once
#include <functional>
#include <vector>
#include "../utils/matrix.hpp"
#include "../utils/autograd.hpp"
};
template<typename T>
class SVM {
public:
int degree = 3, T coef0 = 0.0, T tol = 1e-3, size_t max_iter = 1000, T learning_rate = 0.01);
std::vector<size_t>
support()
const;
std::vector<T>
loss_history()
const {
return loss_history_; }
private:
T C_;
T gamma_;
int degree_;
T coef0_;
T tol_;
size_t max_iter_;
T learning_rate_;
std::vector<size_t> support_indices_;
std::vector<T> dual_coef_;
std::vector<int> classes_;
bool is_fitted_;
std::vector<T> loss_history_;
T gradient_step(
const Matrix<T> &X,
const std::vector<int> &y);
};
using SVMD = SVM<double>;
}
std::vector< size_t > support() const
Get support vector indices.
std::vector< T > decision_function(const Matrix< T > &X) const
Compute the decision function for samples.
Matrix< T > support_vectors() const
Get support vectors.
Matrix< T > predict_proba(const Matrix< T > &X) const
Predict class probabilities for samples.
std::vector< int > predict(const Matrix< T > &X) const
Predict class labels for samples.
void fit(const Matrix< T > &X, const std::vector< int > &y)
Fit the SVM model to training data using automatic differentiation.
T intercept() const
Get intercept term.
std::vector< T > dual_coef() const
Get dual coefficients.
std::vector< T > loss_history() const
Get training loss history.
Variable class that supports automatic differentiation.
Namespace containing traditional machine learning algorithms.
KernelType
Kernel function types for SVM.
@ RBF
Radial Basis Function kernel: K(x, y) = exp(-gamma * ||x - y||^2)
@ LINEAR
Linear kernel: K(x, y) = x^T * y.
@ SIGMOID
Sigmoid kernel: K(x, y) = tanh(gamma * x^T * y + coef0)
@ POLYNOMIAL
Polynomial kernel: K(x, y) = (gamma * x^T * y + coef0)^degree.