• 循环神经网络RNN、RNNCell、GRUCell


    ###################### RNNCell的使用 ####################################
    
    #初始化完全一样
    # input_size - The number of expected features in the input x
    # hidden_size - The number of features in the hidden state h
    # num_layers - Number of recurrent layers, default 1
    
    #但是forward是不一样的
    #ht = rnncell(xt,ht_1)
    x = torch.randn(10, 1, 100)
    rnnCell = nn.RNNCell(input_size=100, hidden_size=30)
    ht = torch.zeros(1, 30)
    out = []
    for xt in x:
        ht = rnnCell(xt, ht)
        out.append(ht)
    print('输出总时间步:', len(out),',每个时间步输出的形状:',out[0].shape)
    
    
    #####################lstm使用#########################
    # 多层RNN的例子
    rnn = nn.LSTM(input_size=100, hidden_size=20, num_layers=4)
    print(rnn)
    x = torch.randn(10, 3, 100)
    out, (h, c) = rnn(x)
    print(out.shape, h.shape, c.shape)
    #输出
    #torch.Size([10, 3, 20]) torch.Size([4, 3, 20]) torch.Size([4, 3, 20])
    
    x = torch.rand(3,3,4)
    id = [0,1]
    c = x[id].transpose(0,1)
    print(x)
    print(c)
    print(c.shape)
    #实例:正弦曲线预测
    
    input_size = 1
    hidden_size = 256
    output_size = 1
    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
            self.rnn = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=2)
            self.linear = nn.Linear(hidden_size, output_size)
    
        def forward(self, x):
            _, (h, c) = self.rnn(x)
            h = h[-1]
            h = self.linear(h)
            return h
    
    
    model = Net()
    criterion = nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    
    
    num_time_steps =200
    start = 0 #在0-3之间随机初始化
    time_steps = np.linspace(start, start+20, num_time_steps)
    data = np.sin(time_steps)
    data = data.reshape(num_time_steps)
    
    horizon_len = 10 #用于估计的时间序列长度
    list = [1, 2, 3]
    
    
    for iter in range(500):
        batch_size = 32
        s = random.sample(range(num_time_steps-horizon_len-1), batch_size)
        train_data_x = []
        train_data_y = []
        for s_i in s:
            train_data_x.append(data[s_i:s_i+horizon_len])
            train_data_y.append(data[s_i + horizon_len])
        train_data_x = torch.tensor(train_data_x, dtype=torch.float32).T
        train_data_x = train_data_x.unsqueeze(2).to(torch.float32)
        train_data_y = torch.tensor(train_data_y, dtype=torch.float64).reshape(-1, batch_size, 1).to(torch.float32)
    
    
        output = model(train_data_x)
    
        loss = criterion(output, train_data_y)
        model.zero_grad()
        loss.backward()
        optimizer.step()
    
        if iter % 50 == 0:
            print("Iteration: {} loss {}".format(iter, loss.item()))
    
    
    num_time_steps =200
    start = 0
    time_steps = np.linspace(start, start+20, num=num_time_steps)
    data = np.sin(time_steps)
    
    predictions1 = []
    
    h = torch.zeros(1, 1, hidden_size)
    c = torch.zeros(1, 1, hidden_size)
    
    input = deque(data[0:horizon_len], maxlen=horizon_len)
    predictions1.extend(data[0:horizon_len])
    for i in range(horizon_len, len(data)*5):
        input_tensor = torch.tensor(input).to(torch.float32)
        input_tensor = input_tensor.view(horizon_len, 1, 1)
        pred= model(input_tensor)
        input.append(pred.detach().numpy().ravel()[0])
        predictions1.append(pred.detach().numpy().ravel()[0])
    
    plt.figure()
    plt.plot(data)
    plt.plot(predictions1)
    plt.legend(['sin wave','pred1'])
    plt.show()
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120

    在这里插入图片描述

  • 相关阅读:
    LeetCode 面试题 08.14. 布尔运算
    (附源码)php养老院管理系统 毕业设计 202026
    102-视频与网络应用篇-环境搭建
    【毕业设计】60-基于ZigBee无线智能消防\烟雾报警逃生系统设计(原理图工程、源代码、低重复率参考文档、实物图)
    SAP S4 FI后台详细配置教程- PART3 (财务凭证相关配置篇)
    现在软件开发app制作还值得做吗
    西班牙知名导演:电影产业应与NFT及社区做结合
    2023年【上海市安全员A证】报名考试及上海市安全员A证试题及解析
    列的类型定义——整形类型
    Day27 Python的部分算法
  • 原文地址:https://blog.csdn.net/keypig_zz/article/details/136166370