File size: 9,403 Bytes
e1e3d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a5ef11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1e3d1e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
---
license: gpl-3.0
language:
- en
pretty_name: Udacity Car Simulator Test Track
size_categories:
- 10K<n<100K
tags:
- vision
- Udacity
- ComputerVision
- DeepLearning
- CNN
- PyTorch
---

# Udacity Car Simulator Dataset

A preprocessed end-to-end driving dataset collected from the [Udacity Self-Driving Car Simulator](https://github.com/udacity/self-driving-car-sim), intended for training a CNN to predict steering angles from camera input.

Collected via manual mouse driving in the simulator and processed into NumPy arrays for fast loading during training. This dataset is used by the [University of Brighton RO501 Coursework project](https://github.com/Jake1402/University-of-Brighton-RO501-Coursework).

---

## Dataset Structure

The dataset consists of four `.npy` files:

| File | Shape | Dtype | Description |
|------|-------|-------|-------------|
| `center.npy` | `(N, 3, 160, 80)` | `float32` | Centre camera frames |
| `left.npy` | `(N, 3, 160, 80)` | `float32` | Left camera frames |
| `right.npy` | `(N, 3, 160, 80)` | `float32` | Right camera frames |
| `steer.npy` | `(M,)` | `float32` | Smoothed steering angles |

Where:
- **N** ≈ 27,000 — number of image frames per camera view
- **M** ≈ 54,000 — number of steering samples (M = 2 × N)
- Images are in **channel-first** format: `(batch, channels, height, width)`
- Color space is **HSV**, pixel values normalised to **[0, 1]**
- Steering values are in the range **[-1, 1]** (negative = left, positive = right)

> **Why M = 2 × N?** The raw simulator log records one row per frame with all three camera paths. During preprocessing, images are sampled every other row (`[::2]`) to reduce redundancy, while the steering signal is kept at full resolution and smoothed. See [Alignment](#aligning-images-and-steering) below for how to pair them up.

---

## Preprocessing Pipeline

The raw data starts as a `driving_log.csv` produced by the simulator with columns:

```
C_img, L_img, R_img, Steer, Accel, Deccel, Velocity
```

Each image goes through the following transformations before being saved:

1. **Crop** — rows `60:135` are kept (the top of the frame contains no useful driving information)
2. **Resize** — to `160 × 80` pixels
3. **Color space** — converted from BGR to HSV
4. **Normalise** — divided by 255 to give values in `[0, 1]`
5. **Reshape** — to channel-first `(3, 160, 80)`

The steering column is smoothed with a **moving average (window = 3)** to remove sudden jerks from manual driving.

---

## Loading the Dataset

### Option 1: Download files directly

Download all four `.npy` files into a local folder (e.g. `npysets/`):

```bash
mkdir npysets
huggingface-cli download JakeWatson/UdacityCarSimDataset --local-dir npysets
```

Or use the `datasets` library:

```python
from huggingface_hub import snapshot_download

snapshot_download(
    repo_id="JakeWatson/UdacityCarSimDataset",
    local_dir="npysets",
    allow_patterns=["*.npy"]
)
```

### Option 2: Load with NumPy

```python
import numpy as np

center = np.load("npysets/center.npy")   # (N, 3, 160, 80) float32
left   = np.load("npysets/left.npy")     # (N, 3, 160, 80) float32
right  = np.load("npysets/right.npy")    # (N, 3, 160, 80) float32
steer  = np.load("npysets/steer.npy")    # (M,) float32

print(center.shape)  # (27xxx, 3, 160, 80)
print(steer.shape)   # (54xxx,)
```

---

## Aligning Images and Steering

Because images were sampled at half the rate of steering, you need to subsample both arrays to align them. The companion project uses:

- **Images:** every 3rd frame → `arr[::3]`
- **Steering:** every 6th value → `arr[::6]`

This gives matching lengths for each camera view:

```python
X_center = np.load("npysets/center.npy")[::3]   # (N/3, 3, 160, 80)
X_left   = np.load("npysets/left.npy")[::3]     # (N/3, 3, 160, 80)
X_right  = np.load("npysets/right.npy")[::3]    # (N/3, 3, 160, 80)
y        = np.load("npysets/steer.npy")[::6]    # (N/3,)

assert X_center.shape[0] == y.shape[0]
```

---

## Building a Training Set

The standard approach (used in the companion project) concatenates all three camera views and offsets the steering label for left/right views to act as data augmentation:

```python
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader

def build_dataset(path="npysets", split=0.95, balance=(31, 550)):
    # Load and align
    X_center = np.load(f"{path}/center.npy")[::3]
    X_left   = np.load(f"{path}/left.npy")[::3]
    X_right  = np.load(f"{path}/right.npy")[::3]
    y        = np.load(f"{path}/steer.npy")[::6]

    # Concatenate views; offset steering for left/right cameras
    X = np.concatenate([X_center, X_left, X_right], axis=0)
    y = np.clip(np.concatenate([y, y + 0.35, y - 0.35]), -1.0, 1.0)

    # Balance by steering frequency (optional but recommended)
    bins, max_per_bin = balance
    bin_edges = np.histogram_bin_edges(y, bins=bins)
    bin_ids = np.digitize(y, bin_edges) - 1
    keep = []
    for b in range(bins):
        idx = np.where(bin_ids == b)[0]
        if len(idx) > max_per_bin:
            idx = np.random.choice(idx, max_per_bin, replace=False)
        keep.append(idx)
    keep = np.concatenate(keep)
    X, y = X[keep], y[keep]

    # Shuffle and split
    perm = np.random.permutation(X.shape[0])
    X, y = X[perm], y[perm]
    split_idx = int(X.shape[0] * split)

    train_ds = TensorDataset(
        torch.from_numpy(X[:split_idx].astype(np.float32)),
        torch.from_numpy(y[:split_idx].astype(np.float32))
    )
    test_ds = TensorDataset(
        torch.from_numpy(X[split_idx:].astype(np.float32)),
        torch.from_numpy(y[split_idx:].astype(np.float32))
    )
    return train_ds, test_ds

train_ds, test_ds = build_dataset()

# Create DataLoaders
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)
test_loader  = DataLoader(test_ds, batch_size=32, shuffle=False)
```

### Why the ±0.35 offset?

The left and right cameras see the road shifted relative to the centre camera. Adding a constant to their steering labels teaches the model that "if I'm looking from the left camera, I need to steer slightly more right to stay centred." This is a form of view-based data augmentation that improves generalisation.

---

## Model Input/Output

The companion CNN (called **UBAC**) expects:

- **Input:** `(batch_size, 3, 160, 80)` — float32 tensor, HSV, normalised [0, 1]
- **Output:** `(batch_size, 1)` — steering angle in `[-1, 1]` (Tanh activation)

```python
import torch
from EffecientRes import ConvolutionalAgent  # from the companion repo

model = ConvolutionalAgent(action_space=1)
x = torch.randn(4, 3, 160, 80)  # batch of 4 images
steering = model(x)              # shape: (4, 1)
```

---

## Quick Start (Full Example)

```python
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader
from torch import nn

# 1. Load data
center = np.load("npysets/center.npy")[::3]
left   = np.load("npysets/left.npy")[::3]
right  = np.load("npysets/right.npy")[::3]
steer  = np.load("npysets/steer.npy")[::6]

# 2. Build augmented dataset
X = np.concatenate([center, left, right], axis=0).astype(np.float32)
y = np.clip(np.concatenate([steer, steer + 0.35, steer - 0.35]), -1, 1).astype(np.float32)

# 3. Shuffle & split
perm = np.random.permutation(X.shape[0])
X, y = X[perm], y[perm]
n_train = int(0.95 * X.shape[0])

train_ds = TensorDataset(torch.from_numpy(X[:n_train]), torch.from_numpy(y[:n_train]))
test_ds  = TensorDataset(torch.from_numpy(X[n_train:]), torch.from_numpy(y[n_train:]))

train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)
test_loader  = DataLoader(test_ds, batch_size=32)

# 4. Define model (from companion repo)
# from EffecientRes import ConvolutionalAgent
# model = ConvolutionalAgent(action_space=1).cuda()

# 5. Training loop
# optimizer = torch.optim.AdamW(model.parameters(), lr=0.0007)
# criterion = nn.SmoothL1Loss()
# for epoch in range(20):
#     for X_batch, y_batch in train_loader:
#         X_batch, y_batch = X_batch.cuda(), y_batch.cuda()
#         pred = model(X_batch).squeeze()
#         loss = criterion(pred, y_batch.squeeze())
#         optimizer.zero_grad()
#         loss.backward()
#         torch.nn.utils.clip_grad_norm_(model.parameters(), 1.5)
#         optimizer.step()
```

---

## Tips

- **Dataset size:** The full dataset is ~12.2 GB. If you're low on disk space, you can subsample further (e.g. `[::6]` for images and `[::12]` for steering) to halve the working set.
- **Balancing matters:** The raw data is heavily skewed toward near-zero steering (driving straight). Without frequency balancing, the model will learn to just hold the wheel.
- **GPU recommended:** Training is fast on a GPU (~minutes per epoch). CPU training works but is slow.
- **Minimum data:** Aim for at least ~50k raw frames (≈ 27k after sampling) for good results.

---

## Citation

If you use this dataset in your work, please cite the original project:

```bibtex
@misc{watson2025udacity,
  author = {Watson, Jake},
  title = {Self-Driving Car Agent — University of Brighton RO501 Coursework},
  year = {2025},
  url = {https://github.com/Jake1402/University-of-Brighton-RO501-Coursework}
}
```

---

## License

This dataset is provided for educational purposes. The images were generated by the Udacity Self-Driving Car Simulator and do not contain any real-world or personal data.