54 const int num_classes,
56 const double learning_rate)
57 : weights_(data[0].size() - 1, 1, true) {
58 assert(data.size() > 0);
60 assert(learning_rate > 0);
61 assert(num_classes >= 1);
62 this->num_classes_ = num_classes;
63 this->epochs_ = epochs;
65 this->learning_rate_ = learning_rate;
66 for (std::vector<double>& row : this->data_) {
67 this->labels_.push_back(row.back());
75 for (
int epoch = 0; epoch < this->epochs_; epoch++) {
76 std::vector<double> y_preds;
79 int e_batch = std::min(batch_size,
int(this->data_.size()));
80 double avg_error = 0.0;
81 std::vector<double> batch_err;
82 std::vector<std::vector<double> > batch_inputs;
83 while (s_batch <
int(this->data_.size())) {
88 for (
int i = s_batch; i < e_batch; i++) {
89 double y_pred_ = (this->weights_.forward(this->data_[i])[0] > 0);
90 double err_ = y_pred_ - this->labels_[i];
91 batch_err.push_back(err_);
93 batch_inputs.push_back(this->data_[i]);
94 y_preds.push_back(y_pred_);
96 avg_error /= (e_batch - s_batch);
98 std::vector<double> avg_gradients(this->data_[0].size(), 0.0);
99 std::vector<std::vector<double> > grad_w(batch_size, std::vector<double>(this->data_[0].size()));
100 for (
int sample = 0; sample < (e_batch - s_batch); sample++) {
101 for (
int features = 0; features < int(batch_inputs[0].size()); features++) {
102 avg_gradients[features] += batch_err[sample] * batch_inputs[sample][features];
105 for (
int features = 0; features < int(avg_gradients.size()); features++) {
106 avg_gradients[features] /= (e_batch - s_batch);
108 this->weights_.update_weights(avg_gradients, avg_error, this->learning_rate_);
111 s_batch = curr_batch * batch_size;
112 e_batch = std::min((curr_batch + 1) * batch_size,
int(this->data_.size()));
115 std::cout <<
"Epoch: " << epoch + 1 <<
": "
perceptron(std::vector< std::vector< double > > const &, const int num_classes, const int epochs=100, const double learning_rate=0.001)
default constructor for perceptron class
Definition perceptron.h:53
void fit(const int batch_size)
fit a single perceptron on the input data
Definition perceptron.h:72
double predict(std::vector< double > const &)
performs inference, classifying to 1 or -1
Definition perceptron.h:123
double f1_score(const std::vector< double > &y, const std::vector< double > &y_pred)
f1 score function: [2 * precision * recall / precision + recall]
Definition metrics.h:99
double accuracy_score(const std::vector< double > &y, const std::vector< double > &y_pred)
accuracy score function[(tp + tn) / (tp + tn + fp + fn)]
Definition metrics.h:81