38 const std::vector<double> &y,
43 std::vector<double> theta(n, 0.0);
46 for (
int iter = 0; iter < num_iters; iter++) {
47 std::vector<double> delta_theta(n,
51 for (
int i = 0; i < m; i++) {
52 double prediction = 0;
53 for (
int j = 0; j < n; j++) {
54 prediction += theta[j] * X[i][j];
56 double error = prediction - y[i];
59 for (
int j = 0; j < n; j++) {
60 delta_theta[j] += error * X[i][j];
65 for (
int j = 0; j < n; j++) {
66 theta[j] -= (alpha / m) * delta_theta[j];
74 const std::vector<std::vector<double>> &X,
75 const std::vector<double> &y,
80 std::vector<double> theta(n, 0.0);
82 std::default_random_engine generator;
83 std::uniform_int_distribution<int> distribution(0, m - 1);
85 for (
int iter = 0; iter < num_iters; iter++) {
87 distribution(generator);
88 double prediction = 0;
90 for (
int j = 0; j < n; j++) {
91 prediction += theta[j] * X[random_index][j];
94 double error = prediction - y[random_index];
96 for (
int j = 0; j < n; j++) {
97 theta[j] -= (alpha * error * X[random_index][j]);
104 const std::vector<std::vector<double>> &X,
105 const std::vector<double> &y,
111 std::vector<double> theta(n, 0.0);
113 std::default_random_engine generator;
114 std::uniform_int_distribution<int> distribution(0, m - 1);
116 for (
int iter = 0; iter < num_iters; iter++) {
118 std::vector<int> batch_indices;
119 for (
int i = 0; i < batch_size; i++) {
120 batch_indices.push_back(distribution(generator));
124 std::vector<double> delta_theta(n, 0.0);
125 for (
int idx : batch_indices) {
126 double prediction = 0;
127 for (
int j = 0; j < n; j++) {
128 prediction += theta[j] * X[idx][j];
130 double error = prediction - y[idx];
132 for (
int j = 0; j < n; j++) {
133 delta_theta[j] += (error * X[idx][j]);
138 for (
int j = 0; j < n; j++) {
139 theta[j] -= (alpha / batch_size) * delta_theta[j];
std::vector< double > minibatch_gradientdesc(const std::vector< std::vector< double >> &X, const std::vector< double > &y, double alpha, int num_iters, int batch_size)
Perform mini-batch gradient descent for linear regression.
std::vector< double > gradientdesc(const std::vector< std::vector< double >> &X, const std::vector< double > &y, double alpha, int num_iters)
Perform gradient descent for linear regression.
std::vector< double > stoch_gradientdesc(const std::vector< std::vector< double >> &X, const std::vector< double > &y, double alpha, int num_iters)
Perform stochastic gradient descent for linear regression.