五十三.网络(3)--区块同步getblocks消息

本文深入剖析比特币节点间区块同步的核心流程,重点讲解getblocks消息的构造与发送机制,包括CBlockLocator定位共同祖先、hashStop终止条件、inv消息的去重发送策略(setInventoryKnown/setInventoryKnown2)、mapAskFor与getdata请求调度,以及block消息接收后通过ProcessBlock完成上链的全过程,涵盖网络层消息序列化(BeginMessage/PushMessage)、缓冲区管理(vSend/vInventoryToSend)及库存去重逻辑。

在节点互发了version消息后,就会发送getblocks消息,请求对方的区块以进行同步。

1.getblocks

在之前我们注释了,节点发送getblocks消息过去,我们来看一下,这个消息是怎么发送的,结构是什么样的。

因为ThreadMessageHandler2,ProcessMessages,之类的函数在之前的章节中已经修复了,从三十章到三十七章有这个过程,所以这里我们基本上不用修复代码,只解释一下代码。

我们来看一下是怎么发送getblocks消息的:

pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), uint256(0));
2.PushMessage

通过PushMessage函数实现的,这个函数有多个重载,根据不同的参数来的,因为不同的消息可能携带不同的参数。

3.CBlockLocator

我们看到,发送getblocks消息,需要两个参数:

CBlockLocator(pindexBest), uint256(0)

他们指明了什么呢?CBlockLocator告诉了对方节点,我当前最优块是什么,以及我有哪些区块。

通过区块哈希值的方式,这组哈希值就存储在这个类里的:

vector<uint256> vHave;

但是这个区块链条哈希,它不是一条不落的记录并发送。

因为这样浪费资源,也没必要。是有一定的算法,比如这样的结构发送过去:

Block Locator:
    Block 1000
    Block 999
    Block 998
    Block 996
    Block 992
    Block 984
    ...
    Genesis Block

具体算法就不说明了,之前的章节中有讲过,当对方节点收到数据后,就会进行对比,找到最近的一个共同祖先。

那后面那个uint256(0)表示什么呢?首先共同的祖先表示同步起始点(假设,你这边需要同步,他那边区块多)。

然后从共同的祖先开始发区块给我,一直碰到区块哈希为uint256(0)就结束,因为没有为0的哈希。

所以这里的意思,就是同步后面所有的区块。

4.BeginMessage

明白了这个后, 我们再来的看一下PushMessage函数定义:

    template<typename T1, typename T2>
    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
    {
        try
        {
            BeginMessage(pszCommand);
            vSend << a1 << a2;
            EndMessage();
        }
        catch (...)
        {
            AbortMessage();
            throw;
        }
    }

BeginMessage就是序列化消息头,就是这个消息的类型啊pszCommand等,具体看函数内部。

然后序列化两个参数。最后消息结束用EndMessage。标准的消息结构发送。这里细节就不追究了。以前也有说过。

5.vSend

我们看到数据最后都是写到了vSend中,即CNode里的vSend中。

然后在ThreadSocketHandler2函数中,遍历vNodes每一个节点,执行这句:

       //
       // Send
       //
       if (FD_ISSET(hSocket, &fdsetSend))
       {
           TRY_CRITICAL_BLOCK(pnode->cs_vSend)
           {
               CDataStream& vSend = pnode->vSend;
               if (!vSend.empty())
               {
                   int nBytes = send(hSocket, &vSend[0], vSend.size(), 0);
                   if (nBytes > 0)
                   {
                       vSend.erase(vSend.begin(), vSend.begin() + nBytes);
                   }
                   else if (nBytes == 0)
                   {
                       if (pnode->ReadyToDisconnect())
                           pnode->vSend.clear();
                   }
                   else
                   {
                       printf("send error %d\n", nBytes);
                       if (pnode->ReadyToDisconnect())
                           pnode->vSend.clear();
                   }
               }
           }
       }

看到里面的send语句了吗,参数就是vSend。

这就是getblocks消息的构造和发送过程。

接下来,我们讲一下,节点收到getblocks消息是怎么处理的。

收到消息数据,解析出消息这些就不说明了,我们直接进入ProcessMessage函数,看处理getblocks消息的代码,如果对上面的步骤感兴趣,可以看上层的的ProcessMessage->ProcessMessages->ThreadMessageHandler2。调用链是从后往前调用,通过处理CNode里的vRecv数据。

这个数据写入到vRecv是在ThreadSocketHandler2函数中的Receive部分处理的,这就是他们的关系。

5.getblocks消息处理

好,在ProcessMessage中收到getblocks消息,处理代码如下:

  else if (strCommand == "getblocks")
  {
      CBlockLocator locator;
      uint256 hashStop;
      vRecv >> locator >> hashStop;

      // Find the first block the caller has in the main chain
      CBlockIndex* pindex = locator.GetBlockIndex();

      // Send the rest of the chain
      if (pindex)
          pindex = pindex->pnext;
      printf("getblocks %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0, 14).c_str());
      for (; pindex; pindex = pindex->pnext)
      {
          if (pindex->GetBlockHash() == hashStop)
          {
              printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0, 14).c_str());
              break;
          }

          // Bypass setInventoryKnown in case an inventory message got lost
          CRITICAL_BLOCK(pfrom->cs_inventory)
          {
              CInv inv(MSG_BLOCK, pindex->GetBlockHash());
              // returns true if wasn't already contained in the set
              if (pfrom->setInventoryKnown2.insert(inv).second)
              {
                  pfrom->setInventoryKnown.erase(inv);
                  pfrom->vInventoryToSend.push_back(inv);
              }
          }
      }
  }
6.locator-hashStop

先直接反序列化出两个参数locator和hashStop,就是对方节点发送getblocks消息带的那两个参数数据。

7.locator.GetBlockIndex

然后是这句:

CBlockIndex* pindex = locator.GetBlockIndex();

根据对方提供的哈希链表,查找共同的祖先。我们按实际的来,首先不管什么情况,共同祖先肯定是有的,因为程序只要运行,就会有一个创世块。

但是构建locator时不是到后面跳着加入吗,那有没有可能把创世块给跳过了呢。

不会,我们具体看这个代码:

 vHave.push_back(hashGenesisBlock);

在构造这个表的时候,结尾处写死了,会把创世块哈希添加进去。

假设有这些情况,比如我这个节点就只有一个创世块。你向我请求,我反而比你的区块还少。

那么就会发生:

  if (pindex)
      pindex = pindex->pnext;

pindex现在是指向创世块,然后它没有下一个,那么这句pindex=pindex->pnext;自然是没有的。

pindex就是为假:

然后这句:

 printf("getblocks %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0, 14).c_str());

也就是说,我一个也没有,不发送,我回应的就是输出getblocks -1 to 0 ,我们在调试界面可以看到。

然后后面的语句是在干什么呢?就是实际发送的代码:

     for (; pindex; pindex = pindex->pnext)
     {
         if (pindex->GetBlockHash() == hashStop)
         {
             printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0, 14).c_str());
             break;
         }

         // Bypass setInventoryKnown in case an inventory message got lost
         CRITICAL_BLOCK(pfrom->cs_inventory)
         {
             CInv inv(MSG_BLOCK, pindex->GetBlockHash());
             // returns true if wasn't already contained in the set
             if (pfrom->setInventoryKnown2.insert(inv).second)
             {
                 pfrom->setInventoryKnown.erase(inv);
                 pfrom->vInventoryToSend.push_back(inv);
             }
         }
     }

这里pindex为false,这个循环自然不会执行,我们假设需要发送。就是我的的区块比你多,同一条链上。

首先就是向后遍历区块,每得到一个就执行一次,当然这里会有hashStop限制,在这里实现停止的。

8.inv

访问这个区块干什么?不是直接发送区块数据给对方。

而是还是先发送这个区块的inv消息过去,对面得到后,对比后,再次发送请求,确定是否需要。

所以这个过程是,getblocks后,对方查找,找到符合你要求的区块,然后发你inv消息,要你确认。当然后续还有过程,流程图是这样:

节点 A                         节点 B
  |                              |
  | -------- getblocks --------> |
  |                              |
  |                     解析 locator 和 hashStop
  |                              |
  |                     查找共同区块
  |                              |
  |                     遍历后续主链区块
  |                              |
  |                     构造 CInv 对象
  |                              |
  |                     加入 vInventoryToSend
  |                              |
  | <--------- inv ------------- |
  |                              |
  | -------- getdata ----------> |
  |                              |
  | <--------- block ----------- |

这里也有一种情况,比如你的区块高度是135,对方是145,因为locator挑选算法,所以找到共同祖先可能是132这个区块。此时虽然对方比你的区块高度还要高,你也还是发送了133,134的inv信息过去了。

当然如果正好是135,那么你就不会发送,也就是你知道了你有的对方都有。

这个这个inv消息,包括两种类型tx和block,然后数据就是对应的哈希值。

9.inv构建和发送

我们来看inv消息的构建和发送。

构造就是这样:

 CInv inv(MSG_BLOCK, pindex->GetBlockHash());

指明是区块inv,以及哈希值,内部具体怎么实现就不看了。

10.vInventoryToSend

然后我们来看这句:

   // returns true if wasn't already contained in the set
   if (pfrom->setInventoryKnown2.insert(inv).second)
   {
       pfrom->setInventoryKnown.erase(inv);
       pfrom->vInventoryToSend.push_back(inv);
   }

它会把这个消息数据加入到vInventoryToSend里面。

但是这里有一段逻辑,即这个inv不存在于setInventoryKnown2中,才能被加入。

而在加入vInventoryToSend之前,还会在setInventoryKnown删除一下这个inv。

这里有三个变量。我们需要知道他们的作用。vInventoryToSend肯定很明白。

就是待发送inv区。

我们来看ThreadMessageHandler2中的SendMessages函数,inv消息发送就是走的SendMessages函数,就是在这里调用的PushMessage函数。

pto->PushMessage("inv", vInventoryToSend);

我们来看相关代码:

   //
   // Message: inventory
   //
   vector<CInv> vInventoryToSend;
   CRITICAL_BLOCK(pto->cs_inventory)
   {
       vInventoryToSend.reserve(pto->vInventoryToSend.size());
       for(const CInv & inv:pto->vInventoryToSend)
       {
           // returns true if wasn't already contained in the set
           if (pto->setInventoryKnown.insert(inv).second)
               vInventoryToSend.push_back(inv);
       }
       pto->vInventoryToSend.clear();
       pto->setInventoryKnown2.clear();
   }
   if (!vInventoryToSend.empty())
       pto->PushMessage("inv", vInventoryToSend);

注意这里发送的"inv"消息是一整个vInventoryToSend,所以节点收到"inv"消息,你不要认为是一条一条发送的。

11.setInventoryKnown

在上面的代码,我们看到setInventoryKnown和setInventoryKnown2的参与。

开始时注意了,先定义一个临时的vInventoryToSend。

然后访问真正的vInventoryToSend,即pto下的。

把它们每一个都加入到setInventoryKnown里面,如果不存在,才能加入到临时的vInventoryToSend里面,什么意思呢,这里第一次是没问题,如果第二次,要发送的inv有一个相同的,那么此时是不是setInventoryKnown已经存在了,所以不会加入到vInventoryToSend里。

也就是说,对该节点已经发送过的inv不会再发送。其他情况。

13.setInventoryKnown2

但这里的setInventoryKnown2是干什么的呢?

只清空了一下:

 pto->setInventoryKnown2.clear();

而且这里:

   // returns true if wasn't already contained in the set
   if (pfrom->setInventoryKnown2.insert(inv).second)
   {
       pfrom->setInventoryKnown.erase(inv);
       pfrom->vInventoryToSend.push_back(inv);
   }

当回复getblocks消息时,待发送inv,它添加的判断也不是根据setInventoryKnown来的,而是根据setInventoryKnown2来判断的,而在具体发送getblocks时,setInventoryKnown2又会被清空,等于这个重复判断在getblocks消息上,通过setInventoryKnown2绕过了。

这是为什么呢,就是这个重复判断不针对getblocks消息的inv,这个优先级比较高,因为同步比较重要。别人请求同步,有可能没成功,是可以再次发送给这个节点。

而其它的比如你收笔了一笔tx,然后再广播这笔tx的inv,就会有这个重复过滤。

或者得到了一个新块也是一样。

这种不能多次重复发送的,否则整个链充斥着大量的广播沉余数据。

比如你发给b,b发给c,c又发给你了。

但是如果能分开写就更好,两套逻辑在同一套业务里有点绕。

因为我实际也没对这种"更好"的设计进行思考,所以有可能会有别的问题。目前这也只是个理论。

好了,了解了inv消息的发送,我们来看收到inv消息是怎么处理的。

14.inv消息的处理

还是在ProcessMessage中:


    else if (strCommand == "inv")
    {
        vector<CInv> vInv;
        vRecv >> vInv;

        CTxDB txdb("r");
        for(const CInv & inv:vInv)
        {
            if (fShutdown)
                return true;
            pfrom->AddInventoryKnown(inv);

            bool fAlreadyHave = AlreadyHave(txdb, inv);
            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");

            if (!fAlreadyHave)
                pfrom->AskFor(inv);
            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
                pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(mapOrphanBlocks[inv.hash]));
        }
    }

注意这里的都没发送就添加到AddInventoryKnown,注意是谁调用的吗,是记录在对方节点里。意思是,对方发送过来的inv,记录一下,如果我从别处又收到了,我就不用再发送给他了。他肯定有。

AlreadyHave

就是判断这个区块和交易我否有,判断方法很简单,索引库对比一下就知道,具体看函数代码,这里不介绍了。

15.mapAskFor

如果没有的话,就是准备请求对方发实际的数据过来,但是这里我们没看到发送具体消息。

只看到了调用了AskFor,这个函数会把inv添加到mapAskFor里面。

   if (!fAlreadyHave)
                pfrom->AskFor(inv);

但是这里还有一种情况,就是就是这块我有了,虽然不要你发送块数据给我,但是这个块是孤儿块。还会有另一个逻辑,就是这句:

 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
     pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(mapOrphanBlocks[inv.hash]));

我们知道有这个逻辑即可,现在不需要过多关注。

我们来看这个mapAskFor.

在SendMessages中:

        //
        // Message: getdata
        //
        vector<CInv> vAskFor;
        int64 nNow = GetTime() * 1000000;
        CTxDB txdb("r");
        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
        {
            const CInv& inv = (*pto->mapAskFor.begin()).second;
            printf("sending getdata: %s\n", inv.ToString().c_str());
            if (!AlreadyHave(txdb, inv))
                vAskFor.push_back(inv);
            pto->mapAskFor.erase(pto->mapAskFor.begin());
        }
        if (!vAskFor.empty())
            pto->PushMessage("getdata", vAskFor);

是在这里发送的,也就是发送getdata消息过去,请求数据,注意这里也不是一条inv发送和一条getdata的,而是带有整个inv请求。vAskFor是inv数组。

当然这里前面还有一些判断,比如再次判断我这里没有这个数据。以及时间判断,就是对inv的getdata请求有着限制,具体逻辑不细究了。非目前重点,有兴趣可自行了解。

好,过了getdata,我们就来看节点收到getdata消息是怎么处理的:

16.getdata

依旧ProcessMessage中:

else if (strCommand == "getdata")
{
    vector<CInv> vInv;
    vRecv >> vInv;

    for(const CInv & inv:vInv)
    {
        if (fShutdown)
            return true;
        printf("received getdata for: %s\n", inv.ToString().c_str());

        if (inv.type == MSG_BLOCK)
        {
            // Send block from disk
            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
            if (mi != mapBlockIndex.end())
            {
                //// could optimize this to send header straight from blockindex for client
                CBlock block;
                block.ReadFromDisk((*mi).second, !pfrom->fClient);
                pfrom->PushMessage("block", block);
            }
        }
        else if (inv.IsKnownType())
        {
            // Send stream from relay memory
            CRITICAL_BLOCK(cs_mapRelay)
            {
                map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
                if (mi != mapRelay.end())
                    pfrom->PushMessage(inv.GetCommand(), (*mi).second);
            }
        }
    }
}

17.block消息

这里我们就尽量简短的说明,快速过一遍。收到getdata消息后,如果请的数据类型是区块,即从磁盘读取,然后发送数据过去,消息类型是block,这个就是真实的区块数据发送。

   CBlock block;
                block.ReadFromDisk((*mi).second, !pfrom->fClient);
                pfrom->PushMessage("block", block);

而如果请求的是tx之类的,则走另一条分支处理。具体逻辑后面再讲。

我们现在主要是同步区块,只要关注block这部分就可以了。

18.block消息处理

还是在ProcessMessage,我们来看收到block消息是怎么处理的:


    else if (strCommand == "block")
    {
        auto_ptr<CBlock> pblock(new CBlock);
        vRecv >> *pblock;

        //// debug print
        printf("received block:\n"); pblock->print();

        CInv inv(MSG_BLOCK, pblock->GetHash());
        pfrom->AddInventoryKnown(inv);

        if (ProcessBlock(pfrom, pblock.release()))
            mapAlreadyAskedFor.erase(inv);
    }

这段代码,之前被我注释了,到了这里我解开了注释,说明我的分析效果很好,如果我们直接测试,是发现不了这个问题的,还是得走一遍流程才能找到问题。

好,收到后恢复出区块数据*pblock;然后最关键的一句来了:

  if (ProcessBlock(pfrom, pblock.release()))
      mapAlreadyAskedFor.erase(inv);

调用的跟挖矿函数同样的上链函数,ProcessBlock,不同的是,第一个参数是有值的,不为null。

ProcessBlock里的事就不用我讲了,在挖矿那里已经详细说明过了。

好,这就是整个同步的过程,下一章中,我们取消version消息处理的这句代码注释:

pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), uint256(0)); 

就能同步区块了,我们在下一章中测试这些功能。

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bczheng1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值