Class Scope類對象是一系列tensorflow操做(ops)所攜帶屬性的集合,這些ops具備類似性質,如:前綴名。ide
本文如下列代碼段爲參考對Class Scope的內部實現細節展開分析。函數
1 Scope root = Scope::NewRootScope(); 2 Scope linear = root.NewSubScope("linear"); 3 // W will be named "linear/W" 4 auto W = Variable(linear.WithOpName("W"),{2, 2}, DT_FLOAT); 5 // b will be named "linear/b" 6 auto b = Variable(linear.WithOpName("b"),{2}, DT_FLOAT); 7 auto x = Const(linear, {...}); // name: "linear/Const" 8 auto m = MatMul(linear, x, W); // name: "linear/MatMul" 9 auto r = BiasAdd(linear, m, b); // name: "linear/BiasAdd"
1 Scope Scope::NewRootScope() { 2 Graph* graph = new Graph(OpRegistry::Global()); 3 ShapeRefiner* refiner = 4 new ShapeRefiner(graph->versions(), graph->op_registry()); 5 return Scope(new Impl(graph, new Status, new Impl::NameMap, refiner, 6 /* disable_shape_inference */ false)); 7 }
---Scope::NewScope() | | | |---new Graph() | |---new ShapeRefiner() | |---Scope(new Impl())
經過調用該靜態成員函數,函數會構造圖結構,同時實例化ShapeRefiner類負責圖對象中節點的上下文初始化,而後利用 前述兩實例化對象實例化Impl類並將其指針做爲參數傳遞給Scope類的構造函數以初始化std::unique_ptr<Impl> impl_成員變量,最後返回初始化後的Scope類對象。在調用Scope構造函數時,傳遞的參數是Impl類型的指針,class Impl (scope_internal.h內給出定義)嵌套在class Scope中,主要負責對Scope類對象中的成員變量進行初始化,如graph_、status_、name_map_等。this
1 /// Return a new scope. Ops created with this scope will have 2 /// `name/child_scope_name` as the prefix. The actual name will be unique 3 /// in the current scope. All other properties are inherited from the current 4 /// scope. If `child_scope_name` is empty, the `/` is elided. 5 Scope NewSubScope(const string& child_scope_name) const;
建立新的scope,在其範圍內的ops的前綴形如:name/child_scope_name,全部其餘的性質從當前的scope繼承而來。spa