简体   繁体   English

在机器学习中使用责任链模式

[英]Using Chain of Responsibility pattern in machine learning

I've read a lot of C++ and Java code of machine learning where each hidden layer is called inside a for loop. 我已经阅读了很多机器学习的C ++和Java代码,其中每个隐藏层都在for循环内调用。 Why is the pattern Chain of Responsability never used ? 为什么从未使用过“责任链 ”模式? What is its disavantages ? 它的缺点是什么?

-Classic approach: -经典方法:

std::vector<Layer> layers(10);
for(Layer& hidden : layers)
  hidden.activation();

-With Chain of Responsability: -带有责任链:

std::vector<Layer*> layers();
// ... init layers vector ...
layers[0]->nextLayer(layers[1]);
layers[1]->nextLayer(layers[2]);
layers[2]->nextLayer(layers[3]);
// and so on...
layers[0]->activation();

In Layer: 在图层中:

Layer::activation()
{
  // do something
  nextLayer->activation();
}

Thank you. 谢谢。

The advantages of the for loop is that the layers collection could be different each time the for loop is called. for循环的优点在于,每次调用for循环时, layers集合可能会有所不同。 The 'disadvantage' is that the for loop is guaranteed to call the member function on every item of the collection. “缺点”是确保for循环可以在集合的每个项目上调用成员函数。

The Chain of Responsibility pattern can be made to 'iterate' through the collection, but it is difficult to change the collection and have to update all the links between items. 可以使“责任链”模式在整个集合中“迭代”,但是很难更改集合并必须更新项目之间的所有链接。 Also, since this is recursion, you could get a stack overflow! 另外,由于这是递归,因此可能会导致堆栈溢出!

However, the Chain of Responsibility really shines when it comes to terminating the loop: Any member can either decide to handle the call itself and return immediately, or just forward to the next item. 但是,当终止循环时,“责任链”确实很出色:任何成员都可以决定自己处理呼叫并立即返回,或者直接转发到下一个项目。

Why to complicate the simple code by creating list and calling it "chain of responsibility"? 为什么通过创建列表并将其称为“责任链”来使简单代码复杂化?

std::vector<Layer> layers(10);
for(Layer& hidden : layers)
{
  // prepare for activation aka do something
  hidden.activation();
}

What you do not like about this approach? 您不喜欢这种方法吗?

The first example; 第一个例子; each layer is completely independent of the next. 每层完全独立于下一层。 This means that they know nothing about other layers - they may or may not exist; 这意味着它们对其他层一无所知-它们可能存在或可能不存在; and have only a need to focus on a single responsibility. 并且只需要专注于单一责任。

The second; 第二; the layers are now not only aware that there are other layers, but also are aware that it's a linked list. 这些图层现在不仅知道还有其他图层,而且还知道这是一个链表。 What if a layer 2 and 3 are independent of each other but just depend on 1? 如果第2层和第3层彼此独立但仅依赖1层怎么办? The ability to represent that is lost. 表达这种能力的能力已经丧失。 Ultimately, the item that controls the layers no longer has any ability to store them how it wants, leading to it being a poor design because it's working towards a god object. 最终,控制图层的项目不再具有存储所需功能的能力,这导致设计不佳,因为它正朝着上帝的目标努力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM