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

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

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

LSTM 簡介:

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

其結(jié)構(gòu)如下:

上述公式不做解釋,我們只要大概記得以下幾個(gè)點(diǎn)就可以了:

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

Pytorch實(shí)現(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)

對比官方實(shí)現(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)

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

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

相關(guān)文章

  • Python 網(wǎng)絡(luò)爬蟲--關(guān)于簡單的模擬登錄實(shí)例講解

    Python 網(wǎng)絡(luò)爬蟲--關(guān)于簡單的模擬登錄實(shí)例講解

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

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

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

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

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

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

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

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

    這篇文章主要給大家介紹了關(guān)于Python中for循環(huán)語句的相關(guān)資料,python中for循環(huán)一般用來迭代字符串,列表,元組等,當(dāng)for循環(huán)用于迭代時(shí)不需要考慮循環(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的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Python使用matplotlib 模塊scatter方法畫散點(diǎn)圖示例

    Python使用matplotlib 模塊scatter方法畫散點(diǎn)圖示例

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

    Python繪圖之turtle庫的基礎(chǔ)語法使用

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

    通過cmd進(jìn)入python的步驟

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

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

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

最新評論

宝应县| 密山市| 呼和浩特市| 湟源县| 抚州市| 太和县| 安义县| 集安市| 古交市| 高密市| 交口县| 临泽县| 勐海县| 鄯善县| 镇沅| 台安县| 门源| 广元市| 德兴市| 河东区| 潮安县| 桂东县| 芷江| 安乡县| 和平县| 黑龙江省| 客服| 琼结县| 溧水县| 鲁甸县| 云阳县| 清河县| 夏邑县| 满洲里市| 靖远县| 徐闻县| 高邮市| 县级市| 象山县| 怀柔区| 镇赉县|