CUDA Networks
neural_network_gradient_descent.cu
Go to the documentation of this file.
1 /**
2  * @file neural_network_gradient_descent.cu
3  * @brief Implementation of the NeuralNetwork::gradient_descent method.
4  */
5 #include "neural_network.h"
6 #include <iostream>
7 #include <iomanip>
8 #include <string>
9 
10 void NeuralNetwork::gradient_descent(const Matrix& X, const Matrix& Y, double learning_rate, int epochs) {
11  const int bar_width = 50;
12  std::string bar;
13 
14  // Iterate through epochs
15  for (int epoch = 0; epoch < epochs; ++epoch) {
16  // Perform forward propagation
17  forward(X);
18 
19  // Perform backward propagation
20  backward(X, Y);
21 
22  // Update parameters
23  update_params(learning_rate);
24 
25  // Calculate accuracy for this epoch
26  double accuracy = get_accuracy(Y);
27 
28  // Calculate progress
29  float progress = static_cast<float>(epoch + 1) / epochs;
30  int pos = static_cast<int>(bar_width * progress);
31 
32  // Update progress bar
33  bar = "[";
34  for (int i = 0; i < bar_width; ++i) {
35  if (i < pos) bar += "=";
36  else if (i == pos) bar += ">";
37  else bar += " ";
38  }
39  bar += "] ";
40 
41  // Print progress bar and accuracy
42  std::cout << "\r" << std::setw(3) << static_cast<int>(progress * 100.0) << "% "
43  << bar << std::setw(3) << epoch + 1 << "/" << std::setw(3) << epochs
44  << " - Accuracy: " << std::fixed << std::setprecision(4) << accuracy << std::flush;
45  }
46  // Move to the next line after completion
47  std::cout << std::endl;
48 }
Represents a matrix with GPU-accelerated operations.
Definition: matrix.h:18
void backward(const Matrix &X, const Matrix &Y)
Perform backward propagation through the network.
void update_params(double learning_rate)
Updates the network parameters based on computed gradients.
double get_accuracy(const Matrix &Y) const
Calculate the accuracy of predictions compared to true labels.
void forward(const Matrix &X)
Perform forward propagation through the network.
void gradient_descent(const Matrix &X, const Matrix &Y, double learning_rate, int epochs)
Perform gradient descent to train the neural network.
Defines the NeuralNetwork class for a simple feedforward neural network.