Skip to content

Commit b71112c

Browse files
authored
Merge pull request #4 from SyntaxSpirits/feature/comprehensive-dropout-testing
feat: Implement dropout regularization and enhance testing
2 parents f08df37 + 8248db9 commit b71112c

21 files changed

Lines changed: 1606 additions & 127 deletions

Cargo.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,17 @@ serde_json = "1.0"
2121
bincode = "1.3"
2222
chrono = { version = "0.4", features = ["serde"] }
2323

24+
[dev-dependencies]
25+
tempfile = "3.0"
26+
2427
[[example]]
2528
name = "training_example"
2629
path = "examples/training_example.rs"
2730

31+
[[example]]
32+
name = "dropout_example"
33+
path = "examples/dropout_example.rs"
34+
2835
[[example]]
2936
name = "stock_prediction"
3037
path = "examples/stock_prediction.rs"

README.md

Lines changed: 111 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Rust-LSTM
22

3-
A comprehensive LSTM (Long Short-Term Memory) neural network library implemented in Rust. This library provides complete functionalities to create, train, and use LSTM networks for various sequence modeling tasks.
3+
A comprehensive LSTM (Long Short-Term Memory) neural network library implemented in Rust. This library provides complete functionalities to create, train, and use LSTM networks for various sequence modeling tasks with advanced dropout regularization.
44

55
## Features
66

@@ -10,8 +10,21 @@ A comprehensive LSTM (Long Short-Term Memory) neural network library implemented
1010
- **Complete training system** with backpropagation through time (BPTT)
1111
- **Multiple optimizers**: SGD, Adam, RMSprop
1212
- **Loss functions**: MSE, MAE, Cross-entropy with softmax
13+
- **Dropout regularization**: Input, recurrent, output dropout and zoneout
1314
- **Training utilities**: gradient clipping, validation, metrics tracking
1415
- **Random initialization** of weights and biases
16+
- **Model persistence**: Save/load models in JSON or binary format
17+
18+
## Dropout Features
19+
20+
The library provides comprehensive dropout support for regularization:
21+
22+
- **Input Dropout**: Applied to inputs before computing gates
23+
- **Recurrent Dropout**: Applied to hidden states (supports variational dropout)
24+
- **Output Dropout**: Applied to LSTM layer outputs
25+
- **Variational Dropout**: Uses same mask across time steps for RNNs
26+
- **Zoneout**: Randomly preserves hidden/cell state values from previous timestep
27+
- **Layer-specific Configuration**: Different dropout settings per layer
1528

1629
## Getting Started
1730

@@ -25,7 +38,7 @@ To use Rust-LSTM in your project, add the following to your Cargo.toml:
2538

2639
```toml
2740
[dependencies]
28-
rust-lstm = "0.1.0"
41+
rust-lstm = "0.2.0"
2942
```
3043

3144
Then, run the following command to build your project and download the Rust-LSTM crate:
@@ -50,7 +63,7 @@ fn main() {
5063
let num_layers = 2;
5164

5265
// Create an LSTM network
53-
let network = LSTMNetwork::new(input_size, hidden_size, num_layers);
66+
let mut network = LSTMNetwork::new(input_size, hidden_size, num_layers);
5467

5568
// Create some example input data
5669
let input = Array2::from_shape_vec((input_size, 1), vec![0.5, 0.1, -0.3]).unwrap();
@@ -67,6 +80,48 @@ fn main() {
6780
}
6881
```
6982

83+
### LSTM with Dropout Regularization
84+
85+
Here's how to create an LSTM network with comprehensive dropout:
86+
87+
```rust
88+
use ndarray::Array2;
89+
use rust_lstm::{LSTMNetwork, LayerDropoutConfig};
90+
91+
fn main() {
92+
let input_size = 10;
93+
let hidden_size = 20;
94+
let num_layers = 3;
95+
96+
// Create network with uniform dropout across all layers
97+
let mut network = LSTMNetwork::new(input_size, hidden_size, num_layers)
98+
.with_input_dropout(0.2, true) // 20% variational input dropout
99+
.with_recurrent_dropout(0.3, true) // 30% variational recurrent dropout
100+
.with_output_dropout(0.1) // 10% output dropout
101+
.with_zoneout(0.05, 0.1); // 5% cell, 10% hidden zoneout
102+
103+
// Or configure dropout per layer for fine-grained control
104+
let layer_configs = vec![
105+
LayerDropoutConfig::new()
106+
.with_input_dropout(0.1, false),
107+
LayerDropoutConfig::new()
108+
.with_recurrent_dropout(0.2, true)
109+
.with_zoneout(0.05, 0.1),
110+
LayerDropoutConfig::new()
111+
.with_output_dropout(0.1),
112+
];
113+
114+
let mut custom_network = LSTMNetwork::new(input_size, hidden_size, num_layers)
115+
.with_layer_dropout(layer_configs);
116+
117+
// Set training mode (enables dropout)
118+
network.train();
119+
120+
// Set evaluation mode (disables dropout)
121+
network.eval();
122+
}
123+
```
124+
70125
### Training an LSTM Network
71126

72127
Here's how to train an LSTM for time series prediction:
@@ -79,8 +134,11 @@ use rust_lstm::optimizers::Adam;
79134
use rust_lstm::loss::MSELoss;
80135

81136
fn main() {
82-
// Create network
83-
let network = LSTMNetwork::new(1, 10, 2);
137+
// Create network with dropout regularization
138+
let network = LSTMNetwork::new(1, 10, 2)
139+
.with_input_dropout(0.2, true)
140+
.with_recurrent_dropout(0.3, true)
141+
.with_output_dropout(0.1);
84142

85143
// Setup training with Adam optimizer
86144
let loss_function = MSELoss;
@@ -98,17 +156,32 @@ fn main() {
98156
// Generate some training data (sine wave prediction)
99157
let train_data = generate_sine_wave_data();
100158

101-
// Train the model
159+
// Train the model (automatically handles train/eval modes)
102160
trainer.train(&train_data, None);
103161

104-
// Make predictions
162+
// Make predictions (automatically sets eval mode)
105163
let predictions = trainer.predict(&input_sequence);
106164
}
107165
```
108166

109167
### Advanced Features
110168

111-
#### Using Different Optimizers
169+
#### Dropout Types
170+
171+
```rust
172+
use rust_lstm::layers::dropout::{Dropout, Zoneout};
173+
174+
// Standard dropout
175+
let mut dropout = Dropout::new(0.3);
176+
177+
// Variational dropout (same mask across time steps)
178+
let mut variational_dropout = Dropout::variational(0.3);
179+
180+
// Zoneout for RNN hidden/cell states
181+
let zoneout = Zoneout::new(0.1, 0.15); // cell_rate, hidden_rate
182+
```
183+
184+
#### Different Optimizers
112185

113186
```rust
114187
use rust_lstm::optimizers::{SGD, Adam, RMSprop};
@@ -143,7 +216,7 @@ let ce_loss = CrossEntropyLoss;
143216
```rust
144217
use rust_lstm::layers::peephole_lstm_cell::PeepholeLSTMCell;
145218

146-
let cell = PeepholeLSTMCell::new(input_size, hidden_size);
219+
let mut cell = PeepholeLSTMCell::new(input_size, hidden_size);
147220
let (h_t, c_t) = cell.forward(&input, &h_prev, &c_prev);
148221
```
149222

@@ -159,28 +232,36 @@ The library includes several examples demonstrating different use cases:
159232

160233
- `basic_usage.rs` - Simple forward pass example
161234
- `training_example.rs` - Complete training workflow with multiple optimizers
235+
- `dropout_example.rs` - Comprehensive dropout regularization demo
162236
- `time_series_prediction.rs` - Time series forecasting
163-
- `text_generation.rs` - Character-level text generation
237+
- `text_generation_advanced.rs` - Character-level text generation
164238
- `multi_layer_lstm.rs` - Multi-layer network usage
165-
- `peephole.rs` - Peephole LSTM variant
239+
- `model_inspection.rs` - Model analysis and debugging utilities
240+
- `stock_prediction.rs` - Financial time series prediction
241+
- `weather_prediction.rs` - Weather forecasting with multiple features
242+
- `real_data_example.rs` - Real-world data loading and processing
166243

167244
Run examples with:
168245

169246
```bash
170247
cargo run --example training_example
248+
cargo run --example dropout_example
171249
cargo run --example time_series_prediction
250+
cargo run --example stock_prediction
251+
cargo run --example weather_prediction
172252
```
173253

174254
## Architecture
175255

176256
The library is organized into several modules:
177257

178-
- **`layers`**: LSTM cell implementations (standard and peephole variants)
179-
- **`models`**: High-level network architectures
258+
- **`layers`**: LSTM cell implementations (standard and peephole variants) with dropout support
259+
- **`models`**: High-level network architectures with configurable dropout
180260
- **`loss`**: Loss functions for training
181261
- **`optimizers`**: Optimization algorithms
182-
- **`training`**: Training utilities and trainer struct
262+
- **`training`**: Training utilities and trainer struct with automatic train/eval mode handling
183263
- **`utils`**: Common utility functions
264+
- **`persistence`**: Model saving and loading functionality
184265

185266
## Training Features
186267

@@ -190,6 +271,17 @@ The library is organized into several modules:
190271
- **Validation Support**: Track validation metrics during training
191272
- **Metrics Tracking**: Loss curves and training progress monitoring
192273
- **Flexible Training Loop**: Configurable epochs, learning rates, and logging
274+
- **Automatic Mode Switching**: Training and evaluation modes for dropout
275+
276+
## Dropout and Regularization
277+
278+
- **Input Dropout**: Regularizes input features
279+
- **Recurrent Dropout**: Regularizes hidden state connections
280+
- **Output Dropout**: Regularizes layer outputs
281+
- **Variational Dropout**: Consistent masks across time steps
282+
- **Zoneout**: RNN-specific regularization technique
283+
- **Layer-specific Configuration**: Fine-grained dropout control
284+
- **Automatic Train/Eval Switching**: Seamless mode management
193285

194286
## Running the Tests
195287

@@ -199,16 +291,14 @@ To run the tests included with Rust-LSTM, execute:
199291
cargo test
200292
```
201293

202-
This will run all the unit and integration tests defined in the library.
294+
## Version History
203295

204-
## Contributing
296+
- **v0.1.0**: Initial LSTM implementation with forward pass
297+
- **v0.2.0**: Complete training system with BPTT, optimizers, and comprehensive dropout support
205298

206-
Contributions to Rust-LSTM are welcome! Here are a few ways you can help:
299+
## Contributing
207300

208-
- Report bugs and issues
209-
- Suggest new features or improvements
210-
- Open a pull request with improvements to code or documentation
211-
- Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests to us.
301+
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
212302

213303
## License
214304

examples/basic_usage.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ fn main() {
77
let num_layers = 2;
88

99
// Create an LSTM network
10-
let network = LSTMNetwork::new(input_size, hidden_size, num_layers);
10+
let mut network = LSTMNetwork::new(input_size, hidden_size, num_layers);
1111

1212
// Create some example input data
1313
let input = Array2::from_shape_vec((input_size, 1), vec![0.5, 0.1, -0.3]).unwrap();

0 commit comments

Comments
 (0)