48.pdf

    1. import torch
    2. from torch import nn
    3. from torch import optim
    4. from torch.nn import functional as F
    5. def main():
    6. rnn = nn.RNN(input_size=100, hidden_size=20, num_layers=1)
    7. print(rnn)
    8. x = torch.randn(10, 3, 100)
    9. out, h = rnn(x, torch.zeros(1, 3, 20))
    10. print(out.shape, h.shape)
    11. rnn = nn.RNN(input_size=100, hidden_size=20, num_layers=4)
    12. print(rnn)
    13. x = torch.randn(10, 3, 100)
    14. out, h = rnn(x, torch.zeros(4, 3, 20))
    15. print(out.shape, h.shape)
    16. # print(vars(rnn))
    17. print('rnn by cell')
    18. cell1 = nn.RNNCell(100, 20)
    19. h1 = torch.zeros(3, 20)
    20. for xt in x:
    21. h1 = cell1(xt, h1)
    22. print(h1.shape)
    23. cell1 = nn.RNNCell(100, 30)
    24. cell2 = nn.RNNCell(30, 20)
    25. h1 = torch.zeros(3, 30)
    26. h2 = torch.zeros(3, 20)
    27. for xt in x:
    28. h1 = cell1(xt, h1)
    29. h2 = cell2(h1, h2)
    30. print(h2.shape)
    31. print('Lstm')
    32. lstm = nn.LSTM(input_size=100, hidden_size=20, num_layers=4)
    33. print(lstm)
    34. x = torch.randn(10, 3, 100)
    35. out, (h, c) = lstm(x)
    36. print(out.shape, h.shape, c.shape)
    37. print('one layer lstm')
    38. cell = nn.LSTMCell(input_size=100, hidden_size=20)
    39. h = torch.zeros(3, 20)
    40. c = torch.zeros(3, 20)
    41. for xt in x:
    42. h, c = cell(xt, [h, c])
    43. print(h.shape, c.shape)
    44. print('two layer lstm')
    45. cell1 = nn.LSTMCell(input_size=100, hidden_size=30)
    46. cell2 = nn.LSTMCell(input_size=30, hidden_size=20)
    47. h1 = torch.zeros(3, 30)
    48. c1 = torch.zeros(3, 30)
    49. h2 = torch.zeros(3, 20)
    50. c2 = torch.zeros(3, 20)
    51. for xt in x:
    52. h1, c1 = cell1(xt, [h1, c1])
    53. h2, c2 = cell2(h1, [h2, c2])
    54. print(h2.shape, c2.shape)
    55. if __name__ == '__main__':
    56. main()