最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用pytorch動手實現(xiàn)LSTM模塊

 更新時間:2022年07月27日 08:53:21   作者:qyhyzard  
這篇文章主要介紹了Python使用pytorch動手實現(xiàn)LSTM模塊,LSTM是RNN中一個較為流行的網(wǎng)絡模塊。主要包括輸入,輸入門,輸出門,遺忘門,激活函數(shù),全連接層(Cell)和輸出

LSTM 簡介:

LSTM是RNN中一個較為流行的網(wǎng)絡模塊。主要包括輸入,輸入門,輸出門,遺忘門,激活函數(shù),全連接層(Cell)和輸出。

其結(jié)構如下:

上述公式不做解釋,我們只要大概記得以下幾個點就可以了:

  • 當前時刻LSTM模塊的輸入有來自當前時刻的輸入值,上一時刻的輸出值,輸入值和隱含層輸出值,就是一共有四個輸入值,這意味著一個LSTM模塊的輸入量是原來普通全連接層的四倍左右,計算量多了許多。
  • 所謂的門就是前一時刻的計算值輸入到sigmoid激活函數(shù)得到一個概率值,這個概率值決定了當前輸入的強弱程度。 這個概率值和當前輸入進行矩陣乘法得到經(jīng)過門控處理后的實際值。
  • 門控的激活函數(shù)都是sigmoid,范圍在(0,1),而輸出輸出單元的激活函數(shù)都是tanh,范圍在(-1,1)。

Pytorch實現(xiàn)如下:

import torch
import torch.nn as nn
from torch.nn import Parameter
from torch.nn import init
from torch import Tensor
import math
class NaiveLSTM(nn.Module):
    """Naive LSTM like nn.LSTM"""
    def __init__(self, input_size: int, hidden_size: int):
        super(NaiveLSTM, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size

        # input gate
        self.w_ii = Parameter(Tensor(hidden_size, input_size))
        self.w_hi = Parameter(Tensor(hidden_size, hidden_size))
        self.b_ii = Parameter(Tensor(hidden_size, 1))
        self.b_hi = Parameter(Tensor(hidden_size, 1))

        # forget gate
        self.w_if = Parameter(Tensor(hidden_size, input_size))
        self.w_hf = Parameter(Tensor(hidden_size, hidden_size))
        self.b_if = Parameter(Tensor(hidden_size, 1))
        self.b_hf = Parameter(Tensor(hidden_size, 1))

        # output gate
        self.w_io = Parameter(Tensor(hidden_size, input_size))
        self.w_ho = Parameter(Tensor(hidden_size, hidden_size))
        self.b_io = Parameter(Tensor(hidden_size, 1))
        self.b_ho = Parameter(Tensor(hidden_size, 1))

        # cell
        self.w_ig = Parameter(Tensor(hidden_size, input_size))
        self.w_hg = Parameter(Tensor(hidden_size, hidden_size))
        self.b_ig = Parameter(Tensor(hidden_size, 1))
        self.b_hg = Parameter(Tensor(hidden_size, 1))

        self.reset_weigths()

    def reset_weigths(self):
        """reset weights
        """
        stdv = 1.0 / math.sqrt(self.hidden_size)
        for weight in self.parameters():
            init.uniform_(weight, -stdv, stdv)

    def forward(self, inputs: Tensor, state: Tuple[Tensor]) \
        -> Tuple[Tensor, Tuple[Tensor, Tensor]]:
        """Forward
        Args:
            inputs: [1, 1, input_size]
            state: ([1, 1, hidden_size], [1, 1, hidden_size])
        """
#         seq_size, batch_size, _ = inputs.size()

        if state is None:
            h_t = torch.zeros(1, self.hidden_size).t()
            c_t = torch.zeros(1, self.hidden_size).t()
        else:
            (h, c) = state
            h_t = h.squeeze(0).t()
            c_t = c.squeeze(0).t()

        hidden_seq = []

        seq_size = 1
        for t in range(seq_size):
            x = inputs[:, t, :].t()
            # input gate
            i = torch.sigmoid(self.w_ii @ x + self.b_ii + self.w_hi @ h_t +
                              self.b_hi)
            # forget gate
            f = torch.sigmoid(self.w_if @ x + self.b_if + self.w_hf @ h_t +
                              self.b_hf)
            # cell
            g = torch.tanh(self.w_ig @ x + self.b_ig + self.w_hg @ h_t
                           + self.b_hg)
            # output gate
            o = torch.sigmoid(self.w_io @ x + self.b_io + self.w_ho @ h_t +
                              self.b_ho)

            c_next = f * c_t + i * g
            h_next = o * torch.tanh(c_next)
            c_next_t = c_next.t().unsqueeze(0)
            h_next_t = h_next.t().unsqueeze(0)
            hidden_seq.append(h_next_t)

        hidden_seq = torch.cat(hidden_seq, dim=0)
        return hidden_seq, (h_next_t, c_next_t)

def reset_weigths(model):
    """reset weights
    """
    for weight in model.parameters():
        init.constant_(weight, 0.5)
### test 
inputs = torch.ones(1, 1, 10)
h0 = torch.ones(1, 1, 20)
c0 = torch.ones(1, 1, 20)
print(h0.shape, h0)
print(c0.shape, c0)
print(inputs.shape, inputs)
# test naive_lstm with input_size=10, hidden_size=20
naive_lstm = NaiveLSTM(10, 20)
reset_weigths(naive_lstm)
output1, (hn1, cn1) = naive_lstm(inputs, (h0, c0))
print(hn1.shape, cn1.shape, output1.shape)
print(hn1)
print(cn1)
print(output1)

對比官方實現(xiàn):

# Use official lstm with input_size=10, hidden_size=20
lstm = nn.LSTM(10, 20)
reset_weigths(lstm)
output2, (hn2, cn2) = lstm(inputs, (h0, c0))
print(hn2.shape, cn2.shape, output2.shape)
print(hn2)
print(cn2)
print(output2)

可以看到與官方的實現(xiàn)有些許的不同,但是輸出的結(jié)果仍舊一致。

到此這篇關于Python使用pytorch動手實現(xiàn)LSTM模塊的文章就介紹到這了,更多相關Python實現(xiàn)LSTM模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python 網(wǎng)絡爬蟲--關于簡單的模擬登錄實例講解

    Python 網(wǎng)絡爬蟲--關于簡單的模擬登錄實例講解

    今天小編就為大家分享一篇Python 網(wǎng)絡爬蟲--關于簡單的模擬登錄實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • python之Django自動化資產(chǎn)掃描的實現(xiàn)

    python之Django自動化資產(chǎn)掃描的實現(xiàn)

    這篇文章主要介紹了python之Django自動化資產(chǎn)掃描的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • 基于pytorch實現(xiàn)對圖片進行數(shù)據(jù)增強

    基于pytorch實現(xiàn)對圖片進行數(shù)據(jù)增強

    圖像數(shù)據(jù)增強是一種在訓練機器學習和深度學習模型時常用的策略,尤其是在計算機視覺領域,具體而言,它通過創(chuàng)建和原始圖像稍有不同的新圖像來擴大訓練集,本文給大家介紹了如何基于pytorch實現(xiàn)對圖片進行數(shù)據(jù)增強,需要的朋友可以參考下
    2024-01-01
  • Python中的條件判斷語句與循環(huán)語句用法小結(jié)

    Python中的條件判斷語句與循環(huán)語句用法小結(jié)

    這篇文章主要介紹了Python中的條件判斷語句與循環(huán)語句用法小結(jié),條件語句和循環(huán)語句是Python程序流程控制的基礎,需要的朋友可以參考下
    2016-03-03
  • Python中for循環(huán)語句實戰(zhàn)案例

    Python中for循環(huán)語句實戰(zhàn)案例

    這篇文章主要給大家介紹了關于Python中for循環(huán)語句的相關資料,python中for循環(huán)一般用來迭代字符串,列表,元組等,當for循環(huán)用于迭代時不需要考慮循環(huán)次數(shù),循環(huán)次數(shù)由后面的對象長度來決定,需要的朋友可以參考下
    2023-09-09
  • python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法

    python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法

    這篇文章主要介紹了python開發(fā)之a(chǎn)naconda以及win7下安裝gensim的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • Python使用matplotlib 模塊scatter方法畫散點圖示例

    Python使用matplotlib 模塊scatter方法畫散點圖示例

    這篇文章主要介紹了Python使用matplotlib 模塊scatter方法畫散點圖,結(jié)合實例形式分析了Python數(shù)值運算與matplotlib模塊圖形繪制相關操作技巧,需要的朋友可以參考下
    2019-09-09
  • Python繪圖之turtle庫的基礎語法使用

    Python繪圖之turtle庫的基礎語法使用

    這篇文章主要給大家介紹了關于Python繪圖之turtle庫的基礎語法使用的相關資料, Turtle庫是Python語言中一個很流行的繪制圖像的函數(shù)庫,再繪圖的時候經(jīng)常需要用到的一個庫需要的朋友可以參考下
    2021-06-06
  • 通過cmd進入python的步驟

    通過cmd進入python的步驟

    在本篇文章里小編給大家整理了關于通過cmd進入python的步驟和實例,需要的朋友們可以參考下。
    2020-06-06
  • 簡單了解Python中的幾種函數(shù)

    簡單了解Python中的幾種函數(shù)

    這篇文章主要介紹了簡單了解Python中的幾種函數(shù),具有一定參考價值。需要的朋友可以了解下。
    2017-11-11

最新評論

三门县| 连山| 岳普湖县| 锦州市| 明光市| 太康县| 淮北市| 滨州市| 天峻县| 连平县| 耿马| 永济市| 佛学| 毕节市| 上高县| 台安县| 称多县| 玛曲县| 大新县| 松江区| 漳平市| 天柱县| 河间市| 沂水县| 镇远县| 安福县| 中阳县| 枝江市| 舟山市| 同德县| 山东省| 阜宁县| 桐庐县| 安国市| 日喀则市| 阳城县| 阿克苏市| 明水县| 江油市| 大荔县| 山东省|