Machine learning basics

Source-owned programs from the current OA SDK. Rust and Python examples follow their respective public APIs.

Rust · Python

The former Fashion-MNIST classifier tutorial has not been admitted to the Rust SDK. This page now points to the current Python ML basics program; a paired Rust regression example is available in the SDK.

Example

This example is currently documented in Python only.

Tu_ml_basics.py

1import oa
2
3engine = oa.Engine()
4
5x = oa.Matrix.from_f32(engine, [5, 1], [-2.0, -1.0, 0.0, 1.0, 2.0])
6target = oa.Matrix.from_f32(engine, [5, 1], [-3.0, -1.0, 1.0, 3.0, 5.0])
7
8model = oa.ml.Linear(engine, 1, 1, seed=0)
9optimizer = oa.ml.Sgd(model.parameters(), learning_rate=0.05)
10
11initial_loss = 0.0
12for step in range(80):
13 optimizer.zero_grad()
14 with oa.ml.GradientTape() as tape:
15 prediction = model.forward(x)
16 loss = oa.ml.loss.mse(prediction, target)
17 tape.backward(loss)
18 optimizer.step()
19 if step == 0:
20 initial_loss = oa.ml.metric.scalar_loss(loss)
21
22final_loss = oa.ml.metric.scalar_loss(loss)
23prediction = model.forward(x)
24values = prediction.read_f32()
25
26assert final_loss < initial_loss * 0.01
27assert max(abs(a - b) for a, b in zip(values, [-3, -1, 1, 3, 5])) < 0.1
28
29print(f"loss: {initial_loss:.6f} -> {final_loss:.6f}")
30print(values)
31

Run Rust tutorials from the OA checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.