| 136 | } |
| 137 | |
| 138 | void expression::backpropagate(std::unordered_map<var, MatrixXd>& leaves){ |
| 139 | std::queue<var> q; |
| 140 | std::unordered_map<var, MatrixXd> derivatives; |
| 141 | std::unordered_map<var, size_t> explored; |
| 142 | q.push(root); |
| 143 | derivatives[root] = ones_like(root); |
| 144 | |
| 145 | while(!q.empty()){ |
| 146 | var v = q.front(); |
| 147 | q.pop(); |
| 148 | std::vector<var>& children = v.getChildren(); |
| 149 | std::vector<MatrixXd> child_derivs = v._back(derivatives[v]); |
| 150 | for(size_t i = 0; i < children.size(); i++){ |
| 151 | auto child = children[i]; |
| 152 | if(explored.find(child) == explored.end()) |
| 153 | explored[child] = child.getParents().size(); |
| 154 | explored[child]--; |
| 155 | if(derivatives.find(child) == derivatives.end()) |
| 156 | derivatives.emplace(child, zeros_like(child)); |
| 157 | derivatives[child] = derivatives[child].array() + child_derivs[i].array(); |
| 158 | if(children[i].getOp() != op_type::none && explored[child] == 0) |
| 159 | q.push(child); |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | for(auto& iter : leaves){ |
| 164 | iter.second = derivatives[iter.first]; |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | void expression::backpropagate(std::unordered_map<var, MatrixXd>& leaves, |
| 169 | const std::vector<var>& nonconsts){ |
no test coverage detected