简体   繁体   中英

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. 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. The 'disadvantage' is that the for loop is guaranteed to call the member function on every item of the collection.

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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