1 #ifndef LOGISTIC_REGRESSION_HPP
2 #define LOGISTIC_REGRESSION_HPP
27 : learningRate_(learningRate), iterations_(iterations), useBias_(useBias) {}
34 void train(
const std::vector<std::vector<double>>& features,
const std::vector<int>& labels) {
35 if (features.empty() || labels.empty()) {
36 throw std::invalid_argument(
"Features and labels must not be empty.");
38 if (features.size() != labels.size()) {
39 throw std::invalid_argument(
"The number of feature vectors must match the number of labels.");
42 size_t numSamples = features.size();
43 size_t numFeatures = features[0].size();
46 for (
const auto& feature : features) {
47 if (feature.size() != numFeatures) {
48 throw std::invalid_argument(
"All feature vectors must have the same number of elements.");
53 if (weights_.empty()) {
54 weights_ = std::vector<double>(numFeatures, 0.0);
60 for (
int iter = 0; iter < iterations_; ++iter) {
61 std::vector<double> gradients(numFeatures, 0.0);
62 double biasGradient = 0.0;
64 for (
size_t i = 0; i < numSamples; ++i) {
66 double error = prediction - labels[i];
68 for (
size_t j = 0; j < numFeatures; ++j) {
69 gradients[j] += error * features[i][j];
73 biasGradient += error;
78 for (
size_t j = 0; j < numFeatures; ++j) {
79 weights_[j] -= learningRate_ * (gradients[j] / numSamples);
83 bias_ -= learningRate_ * (biasGradient / numSamples);
93 int predict(
const std::vector<double>& features)
const {
103 if (features.size() != weights_.size()) {
104 throw std::invalid_argument(
"Feature vector size does not match the number of weights.");
107 double z = std::inner_product(features.begin(), features.end(), weights_.begin(), 0.0);
115 double learningRate_;
117 std::vector<double> weights_;
126 double sigmoid(
double z)
const {
128 double exp_neg_z = std::exp(-z);
129 return 1.0 / (1.0 + exp_neg_z);
131 double exp_z = std::exp(z);
132 return exp_z / (1.0 + exp_z);
Logistic Regression model for binary classification tasks.
Definition: LogisticRegression.hpp:18
void train(const std::vector< std::vector< double >> &features, const std::vector< int > &labels)
Train the model using features and labels.
Definition: LogisticRegression.hpp:34
int predict(const std::vector< double > &features) const
Predicts the class label for a given input.
Definition: LogisticRegression.hpp:93
double predictProbability(const std::vector< double > &features) const
Predicts the probability of class 1 for a given input.
Definition: LogisticRegression.hpp:102
LogisticRegression(double learningRate=0.01, int iterations=1000, bool useBias=true)
Constructor initializing the learning rate and iteration count.
Definition: LogisticRegression.hpp:26