From 96047674e62b3734db42c78013b9ba79c26604ce Mon Sep 17 00:00:00 2001 From: zfan5 Date: Tue, 16 Dec 2025 10:56:59 +0800 Subject: [PATCH] fix(rnn): resolve variable name inconsistency and syntax bug Renamed `model` to `cell` to fix NameError during execution. Also removed a trailing comma in the manual LSTM step that caused unintended tuple assignment. Test: run all --- rnn_implementation.ipynb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/rnn_implementation.ipynb b/rnn_implementation.ipynb index fc5483f..b876476 100644 --- a/rnn_implementation.ipynb +++ b/rnn_implementation.ipynb @@ -53,7 +53,7 @@ "source": [ "import torch\n", "import torch.nn as nn\n", - "model = nn.LSTMCell(20,100)\n", + "cell = nn.LSTMCell(20,100)\n", "print(cell.weight_hh.shape)\n", "print(cell.weight_ih.shape)" ] @@ -81,7 +81,7 @@ "def lstm_cell(x, h, c, W_hh, W_ih, b):\n", " i,f,g,o = np.split(W_ih@x + W_hh@h + b, 4)\n", " i,f,g,o = sigmoid(i), sigmoid(f), np.tanh(g), sigmoid(o)\n", - " c_out = f*c + i*g, \n", + " c_out = f*c + i*g\n", " h_out = o * np.tanh(c_out)\n", " return h_out, c_out" ] @@ -105,7 +105,7 @@ "h0 = np.random.randn(1,100).astype(np.float32)\n", "c0 = np.random.randn(1,100).astype(np.float32)\n", "\n", - "h_, c_ = model(torch.tensor(x), (torch.tensor(h0), torch.tensor(c0)))" + "h_, c_ = cell(torch.tensor(x), (torch.tensor(h0), torch.tensor(c0)))" ] }, { @@ -123,10 +123,10 @@ } ], "source": [ - "h, c = lstm_cell(x[0], h0[0], c0[0], \n", - " model.weight_hh.detach().numpy(), \n", - " model.weight_ih.detach().numpy(), \n", - " (model.bias_hh + model.bias_ih).detach().numpy())\n", + "h, c = lstm_cell(x[0], h0[0], c0[0],\n", + " cell.weight_hh.detach().numpy(),\n", + " cell.weight_ih.detach().numpy(),\n", + " (cell.bias_hh + cell.bias_ih).detach().numpy())\n", "\n", "print(np.linalg.norm(h_.detach().numpy() - h), \n", " np.linalg.norm(c_.detach().numpy() - c))"