caffe中在某一層獲得迭代次數的方法以及caffe編譯時報錯 error: 'to_string' is not a member of 'std'解決方法


https://stackoverflow.com/questions/38369565/how-to-get-learning-rate-or-iteration-times-when-define-new-layer-in-caffe

參考上述網址上的方法,需要修改

common.hpp

  class Caffe {
    public:
      static Caffe& Get();

      ...//Some other public members

      //Returns the current iteration times
      inline static int current_iter() { return Get().cur_iter_; }
      //Sets the current iteration times
      inline static void set_cur_iter(int iter) { Get().cur_iter_ = iter; }

    protected:

      //The variable to save the current itertion times
      int cur_iter_;

      ...//Some other protected members
  }

 

solver.cpp

  template <typename Dtype>
  void Solver<Dtype>::Step(int iters) {

    ...

    while (iter_ < stop_iter) {
      Caffe::set_cur_iter(iter_ );
      ...//Left Operations
    }
  }

 

以及需要獲取迭代次數的layer.cpp

  template <typename Dtype>
  void SomeLayer<Dtype>::some_func() {
    int current_iter = Caffe::current_iter();
    ...//Operations you want
  }

 

再具體的實現過程中出現了獲得的迭代次數都是0的問題,后來請教同事發現是因為多線程造成的。

 

需要修改定義int cur_iter_; 為static int cur_iter_;並且在common.cpp中進行聲明:int Caffe::cur_iter_ = 0;

這樣獲取到的迭代次數就是正確的了。

因為layer是多線程的時候,int current_iter = Caffe::current_iter();這句話會重新初始化一個caffe實例,而不是與solver中共用一個caffe實例,但是將其定義為static類型之后,就是所有實例共享的了,

具體參見:http://blog.csdn.net/morewindows/article/details/6721430

 在C++中,靜態成員是屬於整個類的而不是某個對象,靜態成員變量只存儲一份供所有對象共用。所以在所有對象中都可以共享它。使用靜態成員變量實現多個對象之間的數據共享不會破壞隱藏的原則,保證了安全性還可以節省內存。

靜態成員的定義或聲明要加個關鍵static。靜態成員可以通過雙冒號來使用即<類名>::<靜態成員名>。

 

一。靜態成員函數中不能調用非靜態成員。

二。非靜態成員函數中可以調用靜態成員。因為靜態成員屬於類本身,在類的對象產生之前就已經存在了,所以在非靜態成員函數中是可以調用靜態成員的。

三。靜態成員變量使用前必須先初始化(如int MyClass::m_nNumber = 0;),否則會在linker時出錯。

 

 

 

在調試過程中發現使用to_string函數的時候會報錯,'to_string' is not a member of 'std',查找資料之后,在CMakeLists.txt中添加如下一行即可:

set (CMAKE_CXX_STANDARD 11)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM