mxnet學習(3):autograd

reference:https://mxnet.incubator.apache.org/api/python/autograd/autograd.html

1.基本操作

使用x.attach_grad()爲梯度分配空間,調用with autograd.record()計算梯度,再使用backward()進行反傳

2. BN and dropout

BN, dropout這些層在訓練和測試的時候是不同的,BN在訓練的時候是根據每個mini-batch的均值和方差進行計算並更新參數,在測試的時候是使用訓練集上得到的一個參數進行計算。dropout在測試的時候是沒有的。因此需要在不同的時候加以區別(這一點在pytorch中也是存在)。

使用with autograd.record():,默認爲train_mode = True

也可以使用with autograd.train_mode(),with autograd.predict_mode()或者with autograd.record(train_mode = False)等方式手動控制

3. pause

可以在with autograd.record():中使用with autograd.pause()暫停保存梯度.

eg:

with autograd.record():
    y = model(x)
    backward([y])
    with autograd.pause():
        # testing, IO, gradient updates..
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章