import numpy as np class SimpleRNN: def __init__(self, input_size, hidden_size): self.Wx = np.random.randn(hidden_size, input_size) # 输入权重 self.Wh = np.random.randn(hidden_size, hidden_size) # 隐藏状态权重 self.b = np.zeros((hidden_size, 1)) # 偏置项 def forward(self, x, h_prev): h_next = np.tanh(np.dot(self.Wx, x) + np.dot(self.Wh, h_prev) + self.b) return h_next # 测试 SimpleRNN def test_simple_rnn(): # 参数设置 input_size = 30 # 输入向量的维度 hidden_size = 20 # 隐藏状态的维度 seq_length = 5 # 序列长度 # 初始化 RNN rnn = SimpleRNN(input_size, hidden_size) # 生成随机输入序列 (input_size, seq_length) np.random.seed(42) # 固定随机种子以便复现结果 x_sequence = [np.random.randn(input_size, 1) for _ in range(seq_length)] # 每个时间步的输入 (input_size, 1) # 初始隐藏状态 (hidden_size, 1) h = np.zeros((hidden_size, 1)) # 前向传播 print("RNN 前向传播测试:") for t, x in enumerate(x_sequence): h = rnn.forward(x, h) print(f"时间步 {t}:") print(f"输入 x_{t} 的形状: {x.shape}, 值:\n{x.T}") print(f"隐藏状态 h_{t} 的形状: {h.shape}, 值:\n{h.T}") print("-" * 50) if __name__ == "__main__": test_simple_rnn()