1 #ifndef MULTILINEAR_REGRESSION_HPP
2 #define MULTILINEAR_REGRESSION_HPP
29 : learningRate_(learningRate), iterations_(iterations), lambda_(regularizationParameter) {}
38 void train(
const std::vector<std::vector<double>>& features,
const std::vector<double>& target) {
39 if (features.empty() || features.size() != target.size()) {
40 throw std::invalid_argument(
"Features and target data sizes do not match.");
43 size_t numSamples = features.size();
44 size_t numFeatures = features[0].size();
47 for (
const auto& feature : features) {
48 if (feature.size() != numFeatures) {
49 throw std::invalid_argument(
"All feature vectors must have the same number of elements.");
54 if (weights_.empty()) {
55 weights_.resize(numFeatures, 0.0);
59 for (
int iter = 0; iter < iterations_; ++iter) {
60 gradientDescentStep(features, target);
70 double predict(
const std::vector<double>& features)
const {
71 if (features.size() != weights_.size()) {
72 throw std::invalid_argument(
"Feature vector size does not match the number of weights.");
74 double result = std::inner_product(weights_.begin(), weights_.end(), features.begin(), 0.0);
101 std::vector<double> weights_;
110 void gradientDescentStep(
const std::vector<std::vector<double>>& features,
const std::vector<double>& target) {
111 size_t numSamples = features.size();
112 size_t numFeatures = weights_.size();
114 std::vector<double> gradients(numFeatures, 0.0);
115 double biasGradient = 0.0;
117 for (
size_t i = 0; i < numSamples; ++i) {
118 double prediction =
predict(features[i]);
119 double error = prediction - target[i];
121 for (
size_t j = 0; j < numFeatures; ++j) {
122 gradients[j] += (error * features[i][j]) + (lambda_ * weights_[j]);
125 biasGradient += error;
129 for (
size_t j = 0; j < numFeatures; ++j) {
130 weights_[j] -= (learningRate_ / numSamples) * gradients[j];
133 bias_ -= (learningRate_ / numSamples) * biasGradient;
A class that implements Multilinear Regression for predicting values based on multiple features.
Definition: MultiLinearRegression.hpp:19
void train(const std::vector< std::vector< double >> &features, const std::vector< double > &target)
Trains the Multilinear Regression model on the provided data.
Definition: MultiLinearRegression.hpp:38
double predict(const std::vector< double > &features) const
Predicts the output for a given set of features.
Definition: MultiLinearRegression.hpp:70
double getBias() const
Gets the current bias of the model.
Definition: MultiLinearRegression.hpp:93
std::vector< double > getWeights() const
Gets the current weights of the model.
Definition: MultiLinearRegression.hpp:84
MultilinearRegression(double learningRate=0.01, int iterations=1000, double regularizationParameter=0.0)
Constructs the MultilinearRegression model with the given learning rate and number of iterations.
Definition: MultiLinearRegression.hpp:28