深度学习中的优化算法之SGD

x33g5p2x  于2022-04-06 转载在 其他  
字(13.3k)|赞(0)|评价(0)|浏览(353)

    之前在https://blog.csdn.net/fengbingchun/article/details/75351323 介绍过梯度下降,常见的梯度下降有三种形式:BGD**、SGD****、MBGD****,它们的不同之处在于我们使用多少数据来计算目标函数的梯度**。

    大多数深度学习算法都涉及某种形式的优化。优化指的是改变x以最小化或最大化某个函数f(x)的任务。我们通常以最小化f(x)指代大多数最优化问题。我们把要最小化或最大化的函数称为目标函数(objective function)或准则(criterion)。当我们对其进行最小化时,我们也把它称为成本函数(cost function)、损失函数(loss function)或误差函数(error function)。

    梯度下降是深度学习中一种常用的优化技术。梯度是函数的斜率。它衡量一个变量响应另一个变量的变化而变化的程度。在数学上,梯度下降是一个凸函数,其输出是输入的一组参数的偏导数。梯度越大,坡度越陡(the greater the gradient, the steeper the slope)。从初始值开始,迭代运行梯度下降以找到参数的最佳值,以找到给定成本函数的最小可能值。

    梯度下降是一种优化算法,通常用于寻找深度学习算法中的权值及系数(weights or coefficients),如逻辑回归。它的工作原理是让模型对训练数据进行预测,并使用预测中的error来更新模型从而减少error(It works by having the model make predictions on training data and using the error on the predictions to update the model in such a way as to reduce the error)。

    该算法的目标是找到使模型在训练数据集上的误差最小化的模型参数(e.g. coefficients or weights)。它通过对模型进行更改,使其沿着误差的梯度或斜率向下移动到最小误差值来实现这一点。这使该算法获得了"梯度下降"的名称。

    梯度下降是深度学习中非常流行的优化算法。它的目标是搜索目标函数或成本函数(objective function or cost function)的全局最小值。这只有在目标函数是凸函数时才有可能,这间接意味着该函数将是碗形的。在非凸函数的情况下,梯度下降会找到最近的最小值,这个函数的最小值称为局部最小值。

    梯度下降是一种一阶优化算法。这意味着在更新参数时它只考虑函数的一阶导数。我们的主要目标是在每次迭代中使梯度沿最陡斜率的方向行进,我们在与目标函数的梯度相反的方向上更新参数。

    图解说明:假设只有weight没有bias。如果weight(w)的特定值的斜率>0,则表示我们在最优w的右侧,在这种情况下,更新将是负数,并且w将开始接近最优w。但是,如果weight(w)的特定值的斜率<0,则更新将为正值,并将当前值增加到w以收敛到w*的最佳值。以下截图来自于https://www.machinelearningman.com:重复该方法,直到成本函数收敛。

    在https://blog.csdn.net/fengbingchun/article/details/79370310中有梯度下降应用于二分类的公式推导。

    SGD(Stochastic Gradient Descent):随机梯度下降,通过每个样本迭代更新一次。有时提到SGD的时候,其实指的是MBGD

    梯度下降是一种最小化目标函数的方法:θ为模型的参数,J(θ)为目标函数,以下截图来自https://arxiv.org/pdf/1609.04747.pdf

    在https://blog.csdn.net/fengbingchun/article/details/79648664中也有对SGD的介绍。

    在随机梯度下降中,随机选择几个样本而不是每次迭代整个数据集。在梯度下降中,有一个术语称为”batch”,它表示数据集中用于计算梯度每次迭代的样本数。在BGD中,batch被视为整个数据集。在SGD中,执行每次迭代计算梯度仅使用单个样本,即batch大小为1。被选择用于迭代的样本被随机打乱(randomly shuffled)。

    SGD算法中的一个关键参数是学习率。在实践中,有必要随着时间的推移逐渐降低学习率。SGD中梯度估计引入的噪声源(m个训练样本的随机采样)并不会在极小点处消失。相比之下,当我们使用批量梯度下降到达极小点时,整个代价函数的真实梯度会变得很小,之后为0,因此批量梯度下降可以使用固定的学习率。

    优点:

    (1).频繁的更新可以立即让我们深入了解模型的性能和改进速度。

    (2).这种形式的梯度下降可能是最容易理解和实现的,尤其对于初学者。

    (3).增加的(increased)模型更新频率能够更快地学习某些问题。

    (4).嘈杂的(noisy)的更新过程可以让模型避免局部最小值(如过早收敛)。

    缺点:

    (1).如此频繁地更新模型比其它形式的梯度下降耗费更高计算成本,在大型数据集上训练模型需要更长的时间。

    (2).频繁的更新会导致一个嘈杂的(noisy)梯度信号,这可能会导致模型参数和模型误差跳来跳去(在训练时期具有更高的方差)。

    (3).沿着误差梯度(error gradient)向下的嘈杂学习过程也可能使算法难以确定模型的误差最小值。

    以上内容主要参考:

    1. https://arxiv.org/pdf/1609.04747.pdf

    2. https://machinelearningmastery.com/

    3. https://www.machinelearningman.com

    以下的测试代码以https://blog.csdn.net/fengbingchun/article/details/79346691 中逻辑回归实现的基础上进行调整:

    logistic_regression2.hpp:

  1. #ifndef FBC_SRC_NN_LOGISTIC_REGRESSION2_HPP_
  2. #define FBC_SRC_NN_LOGISTIC_REGRESSION2_HPP_
  3. #include <cstdlib>
  4. #include <ctime>
  5. #include <vector>
  6. #include <string>
  7. #include <memory>
  8. namespace ANN {
  9. enum class ActivationFunction {
  10. Sigmoid // logistic sigmoid function
  11. };
  12. enum class LossFunction {
  13. MSE // Mean Square Error
  14. };
  15. enum class Optimization {
  16. BGD, // Batch Gradient Descent
  17. SGD, // Stochastic Gradient Descent
  18. MBGD // Mini-batch Gradient Descent
  19. };
  20. struct Database {
  21. Database() = default;
  22. std::vector<std::vector<float>> samples; // training set
  23. std::vector<int> labels; // ground truth labels
  24. };
  25. class LogisticRegression2 { // two categories
  26. public:
  27. LogisticRegression2(Optimization optim = Optimization::BGD, int batch_size = 1) : optim_(optim), batch_size_(batch_size) {}
  28. int init(std::unique_ptr<Database> data, int feature_length, float learning_rate = 0.00001, int epochs = 1000);
  29. int train(const std::string& model);
  30. int load_model(const std::string& model);
  31. float predict(const float* data, int feature_length) const; // y = 1/(1+exp(-(wx+b)))
  32. void set_error(float error) { error_ = error; }
  33. private:
  34. int store_model(const std::string& model) const;
  35. float calculate_z(const std::vector<float>& feature) const; // z(i)=w^T*x(i)+b
  36. float calculate_cost_function() const;
  37. static int generate_random(int i) { return std::rand() % i; }
  38. float calculate_activation_function(float value) const;
  39. float calculate_loss_function() const;
  40. float calculate_loss_function_derivative() const;
  41. float calculate_loss_function_derivative(float predictive_value, float true_value) const;
  42. void calculate_gradient_descent(int start = 0, int end = 0);
  43. std::unique_ptr<Database> data_; // train data(images, labels)
  44. std::vector<int> random_shuffle_; // shuffle the training data at every epoch
  45. std::vector<float> o_; // predict value
  46. int epochs_ = 100; // epochs
  47. int m_ = 0; // train samples num
  48. int feature_length_ = 0; // weights length
  49. float alpha_ = 0.00001; // learning rate
  50. std::vector<float> w_; // weights
  51. float b_ = 0.; // threshold
  52. float error_ = 0.00001;
  53. int batch_size_ = 1;
  54. ActivationFunction activation_func_ = ActivationFunction::Sigmoid;
  55. LossFunction loss_func_ = LossFunction::MSE;
  56. Optimization optim_ = Optimization::BGD;
  57. }; // class LogisticRegression2
  58. } // namespace ANN
  59. #endif // FBC_SRC_NN_LOGISTIC_REGRESSION2_HPP_

    logistic_regression2.cpp:

  1. #include "logistic_regression2.hpp"
  2. #include <fstream>
  3. #include <algorithm>
  4. #include <random>
  5. #include <cmath>
  6. #include "common.hpp"
  7. namespace ANN {
  8. int LogisticRegression2::init(std::unique_ptr<Database> data, int feature_length, float learning_rate, int epochs)
  9. {
  10. CHECK(data->samples.size() == data->labels.size());
  11. m_ = data->samples.size();
  12. if (m_ < 2) {
  13. fprintf(stderr, "logistic regression train samples num is too little: %d\n", m_);
  14. return -1;
  15. }
  16. if (learning_rate <= 0) {
  17. fprintf(stderr, "learning rate must be greater 0: %f\n", learning_rate);
  18. return -1;
  19. }
  20. if (epochs < 1) {
  21. fprintf(stderr, "number of epochs cannot be zero or a negative number: %d\n", epochs);
  22. return -1;
  23. }
  24. alpha_ = learning_rate;
  25. epochs_ = epochs;
  26. feature_length_ = feature_length;
  27. data_ = std::move(data);
  28. o_.resize(m_);
  29. return 0;
  30. }
  31. int LogisticRegression2::train(const std::string& model)
  32. {
  33. w_.resize(feature_length_, 0.);
  34. generator_real_random_number(w_.data(), feature_length_, -0.01f, 0.01f, true);
  35. generator_real_random_number(&b_, 1, -0.01f, 0.01f);
  36. if (optim_ == Optimization::BGD) {
  37. for (int iter = 0; iter < epochs_; ++iter) {
  38. calculate_gradient_descent();
  39. auto cost_value = calculate_cost_function();
  40. fprintf(stdout, "epochs: %d, cost function: %f\n", iter, cost_value);
  41. if (cost_value < error_) break;
  42. }
  43. } else {
  44. random_shuffle_.resize(data_->samples.size(), 0);
  45. for (int i = 0; i < data_->samples.size(); ++i)
  46. random_shuffle_[i] = i;
  47. float cost_value = 0.;
  48. for (int iter = 0; iter < epochs_; ++iter) {
  49. std::srand(unsigned(std::time(0)));
  50. std::random_shuffle(random_shuffle_.begin(), random_shuffle_.end(), generate_random);
  51. int loop = (m_ + batch_size_ - 1) / batch_size_;
  52. for (int i = 0; i < loop; ++i) {
  53. int start = i * batch_size_;
  54. int end = start + batch_size_ > m_ ? m_ : start + batch_size_;
  55. calculate_gradient_descent(start, end);
  56. for (int i = 0; i < m_; ++i)
  57. o_[i] = calculate_activation_function(calculate_z(data_->samples[i]));
  58. cost_value = calculate_cost_function();
  59. fprintf(stdout, "epochs: %d, loop: %d, cost function: %f\n", iter, i, cost_value);
  60. if (cost_value < error_) break;
  61. }
  62. if (cost_value < error_) break;
  63. }
  64. }
  65. CHECK(store_model(model) == 0);
  66. return 0;
  67. }
  68. int LogisticRegression2::load_model(const std::string& model)
  69. {
  70. std::ifstream file;
  71. file.open(model.c_str(), std::ios::binary);
  72. if (!file.is_open()) {
  73. fprintf(stderr, "open file fail: %s\n", model.c_str());
  74. return -1;
  75. }
  76. int length{ 0 };
  77. file.read((char*)&length, sizeof(length));
  78. w_.resize(length);
  79. feature_length_ = length;
  80. file.read((char*)w_.data(), sizeof(float)*w_.size());
  81. file.read((char*)&b_, sizeof(float));
  82. file.close();
  83. return 0;
  84. }
  85. float LogisticRegression2::predict(const float* data, int feature_length) const
  86. {
  87. CHECK(feature_length == feature_length_);
  88. float value{0.};
  89. for (int t = 0; t < feature_length_; ++t) {
  90. value += data[t] * w_[t];
  91. }
  92. value += b_;
  93. return (calculate_activation_function(value));
  94. }
  95. int LogisticRegression2::store_model(const std::string& model) const
  96. {
  97. std::ofstream file;
  98. file.open(model.c_str(), std::ios::binary);
  99. if (!file.is_open()) {
  100. fprintf(stderr, "open file fail: %s\n", model.c_str());
  101. return -1;
  102. }
  103. int length = w_.size();
  104. file.write((char*)&length, sizeof(length));
  105. file.write((char*)w_.data(), sizeof(float) * w_.size());
  106. file.write((char*)&b_, sizeof(float));
  107. file.close();
  108. return 0;
  109. }
  110. float LogisticRegression2::calculate_z(const std::vector<float>& feature) const
  111. {
  112. float z{0.};
  113. for (int i = 0; i < feature_length_; ++i) {
  114. z += w_[i] * feature[i];
  115. }
  116. z += b_;
  117. return z;
  118. }
  119. float LogisticRegression2::calculate_cost_function() const
  120. {
  121. /*// J+=-1/m([y(i)*loga(i)+(1-y(i))*log(1-a(i))])
  122. // Note: log0 is not defined
  123. float J{0.};
  124. for (int i = 0; i < m_; ++i)
  125. J += -(data_->labels[i] * std::log(o_[i]) + (1 - labels[i]) * std::log(1 - o_[i]) );
  126. return J/m_;*/
  127. float J{0.};
  128. for (int i = 0; i < m_; ++i)
  129. J += 1./2*std::pow(data_->labels[i] - o_[i], 2);
  130. return J/m_;
  131. }
  132. float LogisticRegression2::calculate_activation_function(float value) const
  133. {
  134. switch (activation_func_) {
  135. case ActivationFunction::Sigmoid:
  136. default: // Sigmoid
  137. return (1. / (1. + std::exp(-value))); // y = 1/(1+exp(-value))
  138. }
  139. }
  140. float LogisticRegression2::calculate_loss_function() const
  141. {
  142. switch (loss_func_) {
  143. case LossFunction::MSE:
  144. default: // MSE
  145. float value = 0.;
  146. for (int i = 0; i < m_; ++i) {
  147. value += 1/2.*std::pow(data_->labels[i] - o_[i], 2);
  148. }
  149. return value/m_;
  150. }
  151. }
  152. float LogisticRegression2::calculate_loss_function_derivative() const
  153. {
  154. switch (loss_func_) {
  155. case LossFunction::MSE:
  156. default: // MSE
  157. float value = 0.;
  158. for (int i = 0; i < m_; ++i) {
  159. value += o_[i] - data_->labels[i];
  160. }
  161. return value/m_;
  162. }
  163. }
  164. float LogisticRegression2::calculate_loss_function_derivative(float predictive_value, float true_value) const
  165. {
  166. switch (loss_func_) {
  167. case LossFunction::MSE:
  168. default: // MSE
  169. return (predictive_value - true_value);
  170. }
  171. }
  172. void LogisticRegression2::calculate_gradient_descent(int start, int end)
  173. {
  174. float db = 0.;
  175. std::vector<float> dw(feature_length_, 0.);
  176. switch (optim_) {
  177. case Optimization::SGD:
  178. case Optimization::MBGD: {
  179. int len = end - start;
  180. std::vector<float> z(len, 0), dz(len, 0);
  181. for (int i = start, x = 0; i < end; ++i, ++x) {
  182. z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
  183. dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);
  184. for (int j = 0; j < feature_length_; ++j) {
  185. dw[j] += data_->samples[random_shuffle_[i]][j] * dz[x]; // dw(i)+=x(i)(j)*dz(i)
  186. }
  187. db += dz[x]; // db+=dz(i)
  188. }
  189. for (int j = 0; j < feature_length_; ++j) {
  190. dw[j] /= len;
  191. w_[j] -= alpha_ * dw[j];
  192. }
  193. b_ -= alpha_ * (db / len);
  194. }
  195. break;
  196. case Optimization::BGD:
  197. default: // BGD
  198. std::vector<float> z(m_, 0), dz(m_, 0);
  199. for (int i = 0; i < m_; ++i) {
  200. z[i] = calculate_z(data_->samples[i]);
  201. o_[i] = calculate_activation_function(z[i]);
  202. dz[i] = calculate_loss_function_derivative(o_[i], data_->labels[i]);
  203. for (int j = 0; j < feature_length_; ++j) {
  204. dw[j] += data_->samples[i][j] * dz[i]; // dw(i)+=x(i)(j)*dz(i)
  205. }
  206. db += dz[i]; // db+=dz(i)
  207. }
  208. for (int j = 0; j < feature_length_; ++j) {
  209. dw[j] /= m_;
  210. w_[j] -= alpha_ * dw[j];
  211. }
  212. b_ -= alpha_ * (db / m_);
  213. }
  214. }
  215. } // namespace ANN

   test_logistic_regression2_gradient_descent:以MNIST为数据集,取0和1,在训练时取训练集各5000张,预测时取测试集各900张

  1. int test_logistic_regression2_gradient_descent()
  2. {
  3. fprintf(stdout,"Warning: first generate test images: execute demo/DatasetToImage/DatasetToImage: MNISTtoImage\n");
  4. fprintf(stdout, "load train images ...\n");
  5. #ifdef _MSC_VER
  6. const std::vector<std::string> image_path{ "E:/GitCode/NN_Test/data/tmp/MNIST/train_images/", "E:/GitCode/NN_Test/data/tmp/MNIST/test_images/"};
  7. const std::string model{ "E:/GitCode/NN_Test/data/logistic_regression2.model" };
  8. #else
  9. const std::vector<std::string> image_path{ "data/tmp/MNIST/train_images/", "data/tmp/MNIST/test_images/"};
  10. const std::string model{ "data/logistic_regression2.model" };
  11. #endif
  12. const int image_size = 28*28;
  13. const int samples_single_class_num = 5000;
  14. auto data1 = std::make_unique<ANN::Database>();
  15. data1->samples.resize(samples_single_class_num*2);
  16. data1->labels.resize(samples_single_class_num*2);
  17. if (read_images(image_path[0], samples_single_class_num, image_size, data1) == -1) return -1;
  18. fprintf(stdout, "start train ...\n");
  19. auto start = std::chrono::steady_clock::now();
  20. //ANN::LogisticRegression2 lr(ANN::Optimization::BGD, samples_single_class_num * 2); // Batch Gradient Descent, epochs = 10000, correct rete: 0.997778
  21. ANN::LogisticRegression2 lr(ANN::Optimization::SGD, 1); // Stochastic Gradient Descent, epochs = 5, correct rete: 0.998889
  22. lr.set_error(0.0002);
  23. int ret = lr.init(std::move(data1), image_size, 0.00001, 5);
  24. if (ret != 0) {
  25. fprintf(stderr, "logistic regression init fail: %d\n", ret);
  26. return -1;
  27. }
  28. ret = lr.train(model);
  29. if (ret != 0) {
  30. fprintf(stderr, "logistic regression train fail: %d\n", ret);
  31. return -1;
  32. }
  33. auto end = std::chrono::steady_clock::now();
  34. fprintf(stdout, "train elapsed time: %d seconds\n", std::chrono::duration_cast<std::chrono::seconds>(end - start).count());
  35. fprintf(stdout, "start predict ...\n");
  36. const int test_single_class_num = 900;
  37. const std::vector<std::string> prefix_name {"0_", "1_"};
  38. ANN::LogisticRegression2 lr2;
  39. lr2.load_model(model);
  40. int count = 0;
  41. for (int i = 1; i <= test_single_class_num; ++i) {
  42. for (const auto& prefix : prefix_name) {
  43. std::string name = std::to_string(i);
  44. if (i < 10) {
  45. name = "0000" + name;
  46. } else if (i < 100) {
  47. name = "000" + name;
  48. } else if (i < 1000) {
  49. name = "00" + name;
  50. }
  51. name = image_path[1] + prefix + name + ".jpg";
  52. cv::Mat mat = cv::imread(name, 0);
  53. if (mat.empty()) {
  54. fprintf(stderr, "read image fail: %s\n", name.c_str());
  55. return -1;
  56. }
  57. if (mat.cols * mat.rows != image_size || mat.channels() != 1) {
  58. fprintf(stderr, "image size fail: width: %d, height: %d, channels: %d\n", mat.cols, mat.rows, mat.channels());
  59. return -1;
  60. }
  61. mat.convertTo(mat, CV_32F);
  62. float probability = lr2.predict((float*)mat.data, image_size);
  63. int label = prefix == "0_" ? 0 : 1;
  64. if ((probability > 0.5 && label == 1) || (probability < 0.5 && label == 0)) ++count;
  65. }
  66. }
  67. float correct_rate = count / (test_single_class_num * 2.);
  68. fprintf(stdout, "correct rate: %f\n", correct_rate);
  69. return 0;
  70. }

    执行结果如下:训练时,SGD成本函数error值并不向BGD一样逐渐减少,偶尔会波动,但是总体上还是逐渐减少;预测准确率为99.94%

    GitHub: https://github.com/fengbingchun/NN_Test

相关文章