Untitled conversation
- Userlua
- Assistant
local LSTM = {}
LSTM.__index = LSTM
function LSTM:new(input_size, hidden_size)
local instance = setmetatable({}, LSTM)
instance.input_size = input_size
instance.hidden_size = hidden_size
instance.Wf = instance:randomMatrix(hidden_size, input_size + hidden_size)
instance.Wi = instance:randomMatrix(hidden_size, input_size + hidden_size)
instance.WC = instance:randomMatrix(hidden_size, input_size + hidden_size)
instance.Wo = instance:randomMatrix(hidden_size, input_size + hidden_size)
instance.bf = instance:zeroVector(hidden_size)
instance.bi = instance:zeroVector(hidden_size)
instance.bC = instance:zeroVector(hidden_size)
instance.bo = instance:zeroVector(hidden_size)
return instance
end
function LSTM:randomMatrix(rows, cols)
local matrix = {}
for i = 1, rows do
matrix[i] = {}
for j = 1, cols do
matrix[i][j] = math.random() * 0.01
end
end
return matrix
end
function LSTM:zeroVector(size)
local vector = {}
for i = 1, size do
vector[i] = 0
end
return vector
end
function LSTM:sigmoid(x)
return 1 / (1 + math.exp(-x))
end
function LSTM:tanh(x)
return math.tanh(x)
end
function LSTM:dot(a, b)
assert(type(a) == "table" and type(b) == "table", "Both arguments must be tables.")
assert(#a == #b, "Vectors must be of the same length.")
local sum = 0
for i = 1, #a do
assert(a[i] ~= nil, "a" .. i .. " is nil") -- Проверка на nil
assert(b[i] ~= nil, "b" .. i .. " is nil")
sum = sum + a[i] * b[i]
end
return sum
end
function LSTM:forward(x_t, h_prev, C_prev)
local combined = {}
for i = 1, #h_prev do
combined[i] = h_prev[i]
end
for i = 1, #x_t do
combined[#h_prev + i] = x_t[i]
end
local f_t, i_t, C_tilde = {}, {}, {}
for i = 1, self.hidden_size do
f_t[i] = self:sigmoid(self:dot(self.Wf[i], combined) + self.bf[i])
i_t[i] = self:sigmoid(self:dot(self.Wi[i], combined) + self.bi[i])
C_tilde[i] = self:tanh(self:dot(self.WC[i], combined) + self.bC[i])
end
local C_t = {}
for i = 1, self.hidden_size do
C_t[i] = f_t[i] * C_prev[i] + i_t[i] * C_tilde[i]
end
local o_t, h_t = {}, {}
for i = 1, self.hidden_size do
o_t[i] = self:sigmoid(self:dot(self.Wo[i], combined) + self.bo[i])
h_t[i] = o_t[i] * self:tanh(C_t[i])
end
return h_t, C_t
end
function LSTM:backward(dh_next, dc_next, x_t, h_prev, C_prev)
local combined = {}
for i = 1, #h_prev do
combined[i] = h_prev[i]
end
for i = 1, #x_t do
combined[#h_prev + i] = x_t[i]
end
local dWf = self:zeroMatrix(self.hidden_size, self.input_size + self.hidden_size)
local dWi = self:zeroMatrix(self.hidden_size, self.input_size + self.hidden_size)
local dWC = self:zeroMatrix(self.hidden_size, self.input_size + self.hidden_size)
local dWo = self:zeroMatrix(self.hidden_size, self.input_size + self.hidden_size)
local dbf, dbi, dBC, dbo = self:zeroVector(self.hidden_size), self:zeroVector(self.hidden_size), self:zeroVector(self.hidden_size), self:zeroVector(self.hidden_size)
for i = 1, self.hidden_size do
local do_t = dh_next[i] * self:tanh(C_prev[i]) * self:sigmoid(self:dot(self.Wo[i], combined) + self.bo[i]) * (1 - self:sigmoid(self:dot(self.Wo[i], combined) + self.bo[i]))
assert(type(do_t) == "number", "do_t must be a number") -- Проверка типов
local dC_t = dh_next[i] * self:dot(self.Wo[i], combined) * (1 - self:tanh(C_prev[i]) ^ 2) + dc_next
assert(type(dC_t) == "number", "dC_t must be a number") -- Проверка типов
local di_t = dC_t * C_tilde[i] * self:sigmoid(self:dot(self.Wi[i], combined) + self.bi[i]) * (1 - self:sigmoid(self:dot(self.Wi[i], combined) + self.bi[i]))
local df_t = dC_t * C_prev[i] * self:sigmoid(self:dot(self.Wf[i], combined) + self.bf[i]) * (1 - self:sigmoid(self:dot(self.Wf[i], combined) + self.bf[i]))
local dC_tilde = dC_t * i_t[i] * (1 - self:tanh(self:dot(self.WC[i], combined) + self.bC[i]) ^ 2)
assert(type(di_t) == "number", "di_t must be a number") -- Проверка типов
assert(type(df_t) == "number", "df_t must be a number")
assert(type(dC_tilde) == "number", "dC_tilde must be a number")
dWf[i] = df_t
dWi[i] = di_t
dWC[i] = dC_tilde
dWo[i] = do_t
dbf[i] = df_t
dbi[i] = di_t
dBC[i] = dC_tilde
dbo[i] = do_t
end
self.Wf = self:matrixAdd(self.Wf, dWf)
self.Wi = self:matrixAdd(self.Wi, dWi)
self.WC = self:matrixAdd(self.WC, dWC)
self.Wo = self:matrixAdd(self.Wo, dWo)
self.bf = self:vectorAdd(self.bf, dbf)
self.bi = self:vectorAdd(self.bi, dbi)
self.bC = self:vectorAdd(self.bC, dBC)
self.bo = self:vectorAdd(self.bo, dbo)
end
function LSTM:zeroMatrix(rows, cols)
local matrix = {}
for i = 1, rows do
matrix[i] = self:zeroVector(cols)
end
return matrix
end
function LSTM:matrixAdd(A, B)
local result = {}
for i = 1, #A do
result[i] = {}
for j = 1, #A[i] do
result[i][j] = A[i][j] + B[i][j]
end
end
return result
end
function LSTM:vectorAdd(A, B)
local result = {}
for i = 1, #A do
result[i] = A[i] + B[i]
end
return result
end
local E_LSTM = {}
E_LSTM.__index = E_LSTM
setmetatable(E_LSTM, {
__index = LSTM
})
function E_LSTM:new(input_size, hidden_size, output_size)
local self = setmetatable({}, E_LSTM)
self.lstm = LSTM:new(input_size, hidden_size)
self.fc_weights = self:randomMatrix(output_size, hidden_size)
self.fc_bias = self:zeroVector(output_size)
return self
end
function E_LSTM:forward(input_sequence)
local h_prev = self.lstm:zeroVector(self.lstm.hidden_size)
local C_prev = self.lstm:zeroVector(self.lstm.hidden_size)
local outputs = {}
for t = 1, #input_sequence do
local x_t = input_sequence[t]
h_prev, C_prev = self.lstm:forward(x_t, h_prev, C_prev)
table.insert(outputs, h_prev)
end
local final_output = {}
for i = 1, #self.fc_weights do
final_output[i] = self:dot(self.fc_weights[i], outputs[#outputs]) + self.fc_bias[i]
end
return final_output
end
function E_LSTM:train(inputs, targets, learning_rate)
for i = 1, #inputs do
local output = self:forward(inputs[i])
local loss = self:calculateLoss(output, targets[i])
local dh_next = self:calculateGradient(output, targets[i]) -- Передаем как градиент
print("Size of dh_next: ", #dh_next) -- Отладочная информация
print("Expected size values: ") -- Вывод значений fc_weights
for j = 1, #self.fc_weights do
if type(self.fc_weights[j]) == "table" then -- Проверяем, что fc_weights[j] - это таблица
for k = 1, #self.fc_weights[j] do
print(string.format("fc_weights[%d][%d]: %f", j, k, self.fc_weights[j][k]))
end
else
print(string.format("fc_weights[%d]: %f", j, self.fc_weights[j]))
end
end
assert(#dh_next == #self.fc_weights, "Gradient size mismatch") -- Проверка на соответствие размеров
self.lstm:backward(dh_next, 0, inputs[i], self.lstm:zeroVector(self.lstm.hidden_size), self.lstm:zeroVector(self.lstm.hidden_size))
end
end
function E_LSTM:calculateLoss(output, target)
local loss = 0
for i = 1, #output do
loss = loss + (output[i] - target[i]) ^ 2
end
return loss / #output
end
function E_LSTM:calculateGradient(output, target)
local gradient = {}
for i = 1, #output do
gradient[i] = 2 * (output[i] - target[i]) / #output -- Производная MSE
end
return gradient
end
return E_LSTM
Найди баги, ошибки, несоответствия в стиле кода, несоответствия в структуре, оптимизируй методы, алгоритмы, формулы, способы, методы.
Your Lua implementation of an LSTM-based neural network exhibits several issues ranging from bugs and logical errors to style inconsistencies and inefficiencies. Below is a comprehensive analysis of these problems along with recommendations for corrections and optimizations.
Issue: In the backward method of the LSTM class, the gradients (dWf, dWi, etc.) are directly added to the weights without considering the learning rate. Moreover, gradients should typically be subtracted from the weights to minimize the loss, not added.
Recommendation:
function LSTM:backward(dWf, dWi, dWC, dWo, dbf, dbi, dBC, dbo, learning_rate)
self.Wf = self:matrixSubtract(self.Wf, self:scalarMultiplyMatrix(dWf, learning_rate))
self.Wi = self:matrixSubtract(self.Wi, self:scalarMultiplyMatrix(dWi, learning_rate))
self.WC = self:matrixSubtract(self.WC, self:scalarMultiplyMatrix(dWC, learning_rate))
self.Wo = self:matrixSubtract(self.Wo, self:scalarMultiplyMatrix(dWo, learning_rate))
self.bf = self:vectorSubtract(self.bf, self:scalarMultiplyVector(dbf, learning_rate))
self.bi = self:vectorSubtract(self.bi, self:scalarMultiplyVector(dbi, learning_rate))
self.bC = self:vectorSubtract(self.bC, self:scalarMultiplyVector(dBC, learning_rate))
self.bo = self:vectorSubtract(self.bo, self:scalarMultiplyVector(dbo, learning_rate))
end
function LSTM:scalarMultiplyMatrix(matrix, scalar)
local result = {}
for i = 1, #matrix do
result[i] = {}
for j = 1, #matrix[i] do
result[i][j] = matrix[i][j] * scalar
end
end
return result
end
function LSTM:scalarMultiplyVector(vector, scalar)
local result = {}
for i = 1, #vector do
result[i] = vector[i] * scalar
end
return result
end
function LSTM:matrixSubtract(A, B)
local result = {}
for i = 1, #A do
result[i] = {}
for j = 1, #A[i] do
result[i][j] = A[i][j] - B[i][j]
end
end
return result
end
function LSTM:vectorSubtract(A, B)
local result = {}
for i = 1, #A do
result[i] = A[i] - B[i]
end
return result
end
Issue: The forward pass does not store intermediate values like f_t, i_t, C_tilde, C_t, and o_t necessary for the backward pass. Without these, accurate gradient computation is impossible.
Recommendation:
function LSTM:forward(x_t, h_prev, C_prev)
local combined = {}
for i = 1, #h_prev do
combined[i] = h_prev[i]
end
for i = 1, #x_t do
combined[#h_prev + i] = x_t[i]
end
local f_t, i_t, C_tilde = {}, {}, {}
for i = 1, self.hidden_size do
f_t[i] = self:sigmoid(self:dot(self.Wf[i], combined) + self.bf[i])
i_t[i] = self:sigmoid(self:dot(self.Wi[i], combined) + self.bi[i])
C_tilde[i] = self:tanh(self:dot(self.WC[i], combined) + self.bC[i])
end
local C_t = {}
for i = 1, self.hidden_size do
C_t[i] = f_t[i] * C_prev[i] + i_t[i] * C_tilde[i]
end
local o_t, h_t = {}, {}
for i = 1, self.hidden_size do
o_t[i] = self:sigmoid(self:dot(self.Wo[i], combined) + self.bo[i])
h_t[i] = o_t[i] * self:tanh(C_t[i])
end
-- Store intermediates for backward pass
self.last_combined = combined
self.last_f = f_t
self.last_i = i_t
self.last_C_tilde = C_tilde
self.last_C_t = C_t
self.last_o = o_t
self.last_h = h_t
return h_t, C_t
end
Issue: The gradient calculations in the backward method are incomplete and incorrect. For instance, gradients like dC_t and di_t are not properly accumulated over time steps, and critical terms are missing.
Recommendation:
Issue: The backward method lacks proper backpropagation through time (BPTT). Gradients from previous time steps are not considered, which is essential for training RNNs like LSTM.
Recommendation:
function E_LSTM:train(inputs, targets, learning_rate)
-- Initialize gradients
local dh_next = self.lstm:zeroVector(self.lstm.hidden_size)
local dc_next = self.lstm:zeroVector(self.lstm.hidden_size)
-- Forward pass to store all intermediates
local h_prev = self.lstm:zeroVector(self.lstm.hidden_size)
local C_prev = self.lstm:zeroVector(self.lstm.hidden_size)
local outputs = {}
for t = 1, #inputs do
local x_t = inputs[t]
h_prev, C_prev = self.lstm:forward(x_t, h_prev, C_prev)
table.insert(outputs, {h_prev = h_prev, C_prev = C_prev})
end
-- Final output
local final_output = {}
for i = 1, #self.fc_weights do
final_output[i] = self:dot(self.fc_weights[i], outputs[#outputs].h_prev) + self.fc_bias[i]
end
-- Calculate loss and gradient
local loss = self:calculateLoss(final_output, targets)
local dh = self:calculateGradient(final_output, targets)
-- Backward pass through FC layer
local dfc_weights = self:zeroMatrix(#self.fc_weights, self.lstm.hidden_size)
local dfc_bias = self:zeroVector(#self.fc_weights)
for i = 1, #self.fc_weights do
for j = 1, self.lstm.hidden_size do
dfc_weights[i][j] = dh[i] * outputs[#outputs].h_prev[j]
end
dfc_bias[i] = dh[i]
end
-- Update FC layer weights
for i = 1, #self.fc_weights do
for j = 1, #self.fc_weights[i] do
self.fc_weights[i][j] = self.fc_weights[i][j] - learning_rate * dfc_weights[i][j]
end
self.fc_bias[i] = self.fc_bias[i] - learning_rate * dfc_bias[i]
end
-- Backward pass through LSTM
local dh_prev = self.lstm:zeroVector(self.lstm.hidden_size)
local dc_prev = self.lstm:zeroVector(self.lstm.hidden_size)
for t = #inputs, 1, -1 do
local dh_total = dh_prev
for i = 1, #dh do
dh_total[i] = dh_total[i] + self.fc_weights[i][1] * dh[i] -- Simplified
end
local x_t = inputs[t]
local h_prev_t = t > 1 and outputs[t-1].h_prev or self.lstm:zeroVector(self.lstm.hidden_size)
local C_prev_t = t > 1 and outputs[t-1].C_prev or self.lstm:zeroVector(self.lstm.hidden_size)
dh_prev, dc_prev = self.lstm:backward(dh_total, dc_prev, x_t, h_prev_t, C_prev_t, learning_rate)
end
end
C_prev in Backward PassIssue: In the backward method, when computing dC_t, self:tanh(C_prev[i]) is used instead of self:tanh(C_t[i]). This is incorrect as C_t is the current cell state, not C_prev.
Recommendation:
h_t[i] = o_t[i] * self:tanh(C_t[i])
In the backward pass:
do_t = dh_next[i] * self:tanh(C_t[i]) * o_t[i] * (1 - o_t[i])
dC_t = dh_next[i] * o_t[i] * (1 - self:tanh(C_t[i])^2) + dc_next[i]
Issue: The current implementation of the backward method only updates the weights based on gradients but does not compute gradients with respect to inputs or propagate them further.
Recommendation:
function LSTM:backward(dh_next, dc_next, x_t, h_prev, C_prev, learning_rate)
-- Compute gradients as before...
-- Update weights using learning rate
-- (As shown in 1.1)
-- Compute gradients w.r. inputs (if necessary)
local dx = {}
for j = 1, #x_t do
dx[j] = 0
for i = 1, self.hidden_size do
dx[j] = dx[j] + self.Wf[i][#h_prev + j] * dWf[i] +
self.Wi[i][#h_prev + j] * dWi[i] +
self.WC[i][#h_prev + j] * dWC[i] +
self.Wo[i][#h_prev + j] * dWo[i]
end
end
return dx, dh_prev, dc_prev
end
Issue: The E_LSTM class is intended to extend LSTM, but inheritance is improperly handled. Specifically, E_LSTM holds an instance of LSTM rather than inheriting its methods directly, leading to redundant code and potential misunderstandings.
Recommendation:
E_LSTM inherit from LSTM using metatables correctly, or compose functionalities clearly.local E_LSTM = setmetatable({}, { __index = LSTM })
E_LSTM.__index = E_LSTM
function E_LSTM:new(input_size, hidden_size, output_size)
local instance = LSTM.new(self, input_size, hidden_size)
instance.output_size = output_size
instance.fc_weights = instance:randomMatrix(output_size, hidden_size)
instance.fc_bias = instance:zeroVector(output_size)
return instance
end
Issue: Combining LSTM and fully connected layers within the same class (E_LSTM) reduces modularity and makes the code harder to maintain or extend.
Recommendation:
local FC = {}
FC.__index = FC
function FC:new(input_size, output_size)
local instance = setmetatable({}, FC)
instance.weights = instance:randomMatrix(output_size, input_size)
instance.bias = instance:zeroVector(output_size)
return instance
end
function FC:forward(input)
local output = {}
for i = 1, #self.weights do
output[i] = self:dot(self.weights[i], input) + self.bias[i]
end
return output
end
-- Similarly, implement backward for FC...
Issue: The E_LSTM class directly accesses and modifies the LSTM instance's attributes, leading to tight coupling.
Recommendation:
Issue: Some comments are in Russian (e.g., -- Проверка на nil), while others are in English.
Recommendation:
-- Example:
assert(a[i] ~= nil, "a[" .. i .. "] is nil")
Issue: Inconsistent use of variable and function naming (e.g., randomMatrix vs. zeroVector).
Recommendation:
function LSTM:random_matrix(rows, cols)
-- Implementation...
end
function LSTM:zero_vector(size)
-- Implementation...
end
Issue: Functions lack descriptive comments explaining their purpose, inputs, and outputs.
Recommendation:
--- Generates a matrix with random values
-- @param rows Number of rows
-- @param cols Number of columns
-- @return A matrix represented as a table of tables
function LSTM:random_matrix(rows, cols)
-- Implementation...
end
Issue: Using Lua tables of tables for matrices and tables for vectors is inefficient and leads to slower computations, especially for large matrices.
Recommendation:
Issue: Multiple calls to self:dot(self.Wx[i], combined) compute the same dot product repeatedly within the backward pass.
Recommendation:
Issue: All operations are performed element-wise using loops, which is slow in Lua.
Recommendation:
Issue: The randomMatrix function initializes weights with small random values, but more sophisticated initialization techniques (like Xavier or He initialization) can improve training.
Recommendation:
randomMatrix to incorporate these methods.function LSTM:random_matrix(rows, cols)
local matrix = {}
local std = math.sqrt(2.0 / (rows + cols))
for i = 1, rows do
matrix[i] = {}
for j = 1, cols do
matrix[i][j] = (math.random() * 2 - 1) * std
end
end
return matrix
end
Issue: The current model lacks regularization, which can lead to overfitting.
Recommendation:
Issue: Using the standard sigmoid and tanh can lead to vanishing gradients.
Recommendation:
ReLU or Leaky ReLU where appropriate.function LSTM:relu(x)
return math.max(0, x)
end
Issue: Gradients can explode, especially in deep networks.
Recommendation:
function LSTM:clip_gradients(grad, clip_value)
for i = 1, #grad do
if grad[i] > clip_value then
grad[i] = clip_value
elseif grad[i] < -clip_value then
grad[i] = -clip_value
end
end
return grad
end
Issue: The training loop lacks batching, shuffling, and other optimization techniques.
Recommendation:
Below is a refactored and optimized version of your LSTM and E_LSTM classes incorporating many of the recommendations above. Note that due to the complexity of LSTM backpropagation, this example focuses on structure and key corrections. You may need to further refine gradient calculations and BPTT implementation.
After implementing the above corrections and optimizations, it's crucial to rigorously test your model:
dot, forward, and backward to ensure they work as expected.By addressing the aforementioned issues and implementing the recommended optimizations, your LSTM implementation in Lua will become more robust, efficient, and maintainable. Building neural networks from scratch is intricate, and leveraging existing libraries or frameworks can save time and reduce potential errors. However, understanding the underlying mechanics, as you're doing, is invaluable for customizing and optimizing models for specific tasks.
Not yet included in a published release.
Note: The above is a simplified illustration. Implementing full BPTT requires storing all intermediate states during the forward pass and correctly propagating gradients through each time step.
-- LSTM.lua
local LSTM = {}
LSTM.__index = LSTM
-- Initialize LSTM with advanced initialization and better structure
function LSTM:new(input_size, hidden_size, learning_rate)
local instance = setmetatable({}, LSTM)
instance.input_size = input_size
instance.hidden_size = hidden_size
instance.learning_rate = learning_rate or 0.01
-- Initialize weights with Xavier initialization
instance.Wf = instance:random_matrix(hidden_size, input_size + hidden_size)
instance.Wi = instance:random_matrix(hidden_size, input_size + hidden_size)
instance.WC = instance:random_matrix(hidden_size, input_size + hidden_size)
instance.Wo = instance:random_matrix(hidden_size, input_size + hidden_size)
instance.bf = instance:zero_vector(hidden_size)
instance.bi = instance:zero_vector(hidden_size)
instance.bC = instance:zero_vector(hidden_size)
instance.bo = instance:zero_vector(hidden_size)
return instance
end
--- Generates a matrix with Xavier initialization
function LSTM:random_matrix(rows, cols)
local matrix = {}
local std = math.sqrt(2.0 / (rows + cols))
for i = 1, rows do
matrix[i] = {}
for j = 1, cols do
matrix[i][j] = (math.random() * 2 - 1) * std
end
end
return matrix
end
--- Generates a zero vector of given size
function LSTM:zero_vector(size)
local vector = {}
for i = 1, size do
vector[i] = 0
end
return vector
end
--- Sigmoid activation function
function LSTM:sigmoid(x)
return 1 / (1 + math.exp(-x))
end
--- Tanh activation function
function LSTM:tanh(x)
return math.tanh(x)
end
--- Dot product of two vectors
function LSTM:dot(a, b)
assert(type(a) == "table" and type(b) == "table", "Both arguments must be tables.")
assert(#a == #b, "Vectors must be of the same length.")
local sum = 0
for i = 1, #a do
assert(a[i] ~= nil, "a[" .. i .. "] is nil")
assert(b[i] ~= nil, "b[" .. i .. "] is nil")
sum = sum + a[i] * b[i]
end
return sum
end
--- Forward pass through LSTM cell
function LSTM:forward(x_t, h_prev, C_prev)
local combined = {}
for i = 1, #h_prev do
combined[i] = h_prev[i]
end
for i = 1, #x_t do
combined[#h_prev + i] = x_t[i]
end
-- Gates
local f_t, i_t, C_tilde, o_t = {}, {}, {}, {}
for i = 1, self.hidden_size do
f_t[i] = self:sigmoid(self:dot(self.Wf[i], combined) + self.bf[i])
i_t[i] = self:sigmoid(self:dot(self.Wi[i], combined) + self.bi[i])
C_tilde[i] = self:tanh(self:dot(self.WC[i], combined) + self.bC[i])
end
-- Cell state
local C_t = {}
for i = 1, self.hidden_size do
C_t[i] = f_t[i] * C_prev[i] + i_t[i] * C_tilde[i]
end
-- Output gate and hidden state
for i = 1, self.hidden_size do
o_t[i] = self:sigmoid(self:dot(self.Wo[i], combined) + self.bo[i])
end
local h_t = {}
for i = 1, self.hidden_size do
h_t[i] = o_t[i] * self:tanh(C_t[i])
end
-- Store intermediates for backward pass
self.last_combined = combined
self.last_f = f_t
self.last_i = i_t
self.last_C_tilde = C_tilde
self.last_C_prev = C_prev
self.last_C_t = C_t
self.last_o = o_t
self.last_h_prev = h_prev
return h_t, C_t
end
--- Backward pass through LSTM cell
function LSTM:backward(dh_next, dc_next, learning_rate)
local dWf = self:zero_matrix(self.hidden_size, #self.last_combined)
local dWi = self:zero_matrix(self.hidden_size, #self.last_combined)
local dWC = self:zero_matrix(self.hidden_size, #self.last_combined)
local dWo = self:zero_matrix(self.hidden_size, #self.last_combined)
local dbf, dbi, dBC, dbo = self:zero_vector(self.hidden_size), self:zero_vector(self.hidden_size), self:zero_vector(self.hidden_size), self:zero_vector(self.hidden_size)
local dC = {}
for i = 1, self.hidden_size do
dC[i] = dh_next[i] * self.last_o[i] * (1 - self:tanh(self.last_C_t[i])^2) + dc_next[i]
end
local dh_prev = self:zero_vector(self.hidden_size)
local dc_prev = self:zero_vector(self.hidden_size)
for i = 1, self.hidden_size do
-- Output gate gradients
local do_t = dh_next[i] * self:tanh(self.last_C_t[i]) * self.last_o[i] * (1 - self.last_o[i])
-- Cell state gradients
local dC_t = dC[i]
local df_t = dC_t * self.last_C_prev[i] * self.last_f[i] * (1 - self.last_f[i])
local di_t = dC_t * self.last_C_tilde[i] * self.last_i[i] * (1 - self.last_i[i])
local dC_tilde = dC_t * self.last_i[i] * (1 - self.last_C_tilde[i]^2)
-- Accumulate gradients
dWf[i] = self:vector_add(dWf[i], self:scalar_multiply_vector(df_t, self.last_combined))
dWi[i] = self:vector_add(dWi[i], self:scalar_multiply_vector(di_t, self.last_combined))
dWC[i] = self:vector_add(dWC[i], self:scalar_multiply_vector(dC_tilde, self.last_combined))
dWo[i] = self:vector_add(dWo[i], self:scalar_multiply_vector(do_t, self.last_combined))
dbf[i] = dbf[i] + df_t
dbi[i] = dbi[i] + di_t
dBC[i] = dBC[i] + dC_tilde
dbo[i] = dbo[i] + do_t
-- Gradients w.r.t. inputs and h_prev
for j = 1, #self.last_combined do
dh_prev[j] = dh_prev[j] + self.Wf[i][j] * df_t +
self.Wi[i][j] * di_t +
self.WC[i][j] * dC_tilde +
self.Wo[i][j] * do_t
end
-- Gradients w.r.t. C_prev
dc_prev[i] = dC_t * self.last_f[i]
end
-- Update weights and biases
self.Wf = self:matrix_subtract(self.Wf, self:scalar_multiply_matrix(dWf, learning_rate))
self.Wi = self:matrix_subtract(self.Wi, self:scalar_multiply_matrix(dWi, learning_rate))
self.WC = self:matrix_subtract(self.WC, self:scalar_multiply_matrix(dWC, learning_rate))
self.Wo = self:matrix_subtract(self.Wo, self:scalar_multiply_matrix(dWo, learning_rate))
self.bf = self:vector_subtract(self.bf, self:scalar_multiply_vector(dbf, learning_rate))
self.bi = self:vector_subtract(self.bi, self:scalar_multiply_vector(dbi, learning_rate))
self.bC = self:vector_subtract(self.bC, self:scalar_multiply_vector(dBC, learning_rate))
self.bo = self:vector_subtract(self.bo, self:scalar_multiply_vector(dbo, learning_rate))
-- Gradient clipping (optional)
-- Implement if necessary
return dh_prev, dc_prev
end
--- Generates a zero matrix of given dimensions
function LSTM:zero_matrix(rows, cols)
local matrix = {}
for i = 1, rows do
matrix[i] = self:zero_vector(cols)
end
return matrix
end
--- Adds two matrices
function LSTM:matrix_add(A, B)
local result = {}
for i = 1, #A do
result[i] = {}
for j = 1, #A[i] do
result[i][j] = A[i][j] + B[i][j]
end
end
return result
end
--- Subtracts matrix B from A
function LSTM:matrix_subtract(A, B)
local result = {}
for i = 1, #A do
result[i] = {}
for j = 1, #A[i] do
result[i][j] = A[i][j] - B[i][j]
end
end
return result
end
--- Adds two vectors
function LSTM:vector_add(A, B)
local result = {}
for i = 1, #A do
result[i] = A[i] + B[i]
end
return result
end
--- Subtracts vector B from A
function LSTM:vector_subtract(A, B)
local result = {}
for i = 1, #A do
result[i] = A[i] - B[i]
end
return result
end
--- Multiplies a vector by a scalar and returns a new vector
function LSTM:scalar_multiply_vector(scalar, vector)
local result = {}
for i = 1, #vector do
result[i] = scalar * vector[i]
end
return result
end
--- Multiplies two vectors element-wise
function LSTM:elementwise_multiply(a, b)
assert(#a == #b, "Vectors must be of the same length for element-wise multiplication.")
local result = {}
for i = 1, #a do
result[i] = a[i] * b[i]
end
return result
end
--- Adds two vectors
function LSTM:vector_add(A, B)
local result = {}
for i = 1, #A do
result[i] = A[i] + B[i]
end
return result
end
return LSTM
-- E_LSTM.lua
local LSTM = require("LSTM")
local E_LSTM = {}
E_LSTM.__index = E_LSTM
setmetatable(E_LSTM, {
__index = LSTM
})
function E_LSTM:new(input_size, hidden_size, output_size, learning_rate)
local instance = LSTM.new(self, input_size, hidden_size, learning_rate)
instance.output_size = output_size
instance.fc_weights = instance:random_matrix(output_size, hidden_size)
instance.fc_bias = instance:zero_vector(output_size)
return instance
end
--- Forward pass through the entire E_LSTM network
function E_LSTM:forward(input_sequence)
local h_prev = self:zero_vector(self.hidden_size)
local C_prev = self:zero_vector(self.hidden_size)
local outputs = {}
for t = 1, #input_sequence do
local x_t = input_sequence[t]
h_prev, C_prev = self:forward(x_t, h_prev, C_prev)
table.insert(outputs, h_prev)
end
-- Fully connected layer on last hidden state
local final_output = {}
for i = 1, self.output_size do
final_output[i] = self:dot(self.fc_weights[i], outputs[#outputs]) + self.fc_bias[i]
end
self.last_output = final_output
self.last_hidden = outputs[#outputs]
return final_output
end
--- Calculates Mean Squared Error loss
function E_LSTM:calculate_loss(output, target)
local loss = 0
for i = 1, #output do
loss = loss + (output[i] - target[i])^2
end
return loss / #output
end
--- Calculates gradient of loss w.r. to output
function E_LSTM:calculate_gradient(output, target)
local gradient = {}
for i = 1, #output do
gradient[i] = 2 * (output[i] - target[i]) / #output
end
return gradient
end
--- Trains the model on a single input-target pair
function E_LSTM:train(input_sequence, target)
-- Forward pass
local output = self:forward(input_sequence)
local loss = self:calculate_loss(output, target)
-- Calculate gradients
local dL_dy = self:calculate_gradient(output, target)
-- Backpropagate through FC layer
local dL_dfc_weights = {}
local dL_dfc_bias = {}
for i = 1, self.output_size do
dL_dfc_bias[i] = dL_dy[i]
dL_dfc_weights[i] = {}
for j = 1, self.hidden_size do
dL_dfc_weights[i][j] = dL_dy[i] * self.last_hidden[j]
end
end
-- Update FC layer weights and biases
for i = 1, self.output_size do
for j = 1, self.hidden_size do
self.fc_weights[i][j] = self.fc_weights[i][j] - self.learning_rate * dL_dfc_weights[i][j]
end
self.fc_bias[i] = self.fc_bias[i] - self.learning_rate * dL_dfc_bias[i]
end
-- Calculate gradient w.r. to last hidden state
local dL_dh = {}
for j = 1, self.hidden_size do
dL_dh[j] = 0
for i = 1, self.output_size do
dL_dh[j] = dL_dh[j] + self.fc_weights[i][j] * dL_dy[i]
end
end
-- Backward pass through LSTM
local dh_next = dL_dh
local dc_next = self:zero_vector(self.hidden_size)
-- Assuming the last time step is t=#input_sequence
dh_next, dc_next = self:backward(dh_next, dc_next, self.last_hidden, self.last_hidden, self.last_hidden, self.learning_rate)
print(string.format("Loss: %.6f", loss))
end
return E_LSTM