pymlkit
API reference

Network

The Network class and all of its methods.

Network owns a C network struct and frees it when the Python object is garbage collected. Every operation is a method on it.

python
from pymlkit import Network

Network()

Network(input_size: int)

Creates an empty network that accepts input_size numbers per sample. Add layers with add_dense before training.

Attributes: input_size and output_size. The latter is the neuron count of the most recently added layer, and starts at 1.

add_dense

add_dense(neuron_count: int, activation: Activations = Activations.Linear)

Appends a fully connected layer. Layers are applied in the order they are added.

ParameterTypeDescription
neuron_countintNumber of neurons, which is the width of this layer's output.
activationActivationsNon-linearity applied to the layer. Defaults to Linear.

set_loss

set_loss(loss: Losses = Losses.HalfMSE)

Selects the loss minimised by fit and backward. See Losses.

fit

fit(train_x, train_y, lr=0.01, epochs=10, batch=1, log_step=10)

Trains with mini-batch stochastic gradient descent. Returns nothing.

ParameterTypeDescription
train_xlist[float]All samples concatenated. Length must be a multiple of input_size.
train_ylist[float]All targets concatenated. Length must equal samples × output_size.
lrfloatLearning rate.
epochsintFull passes over the data.
batchintSamples per gradient step.
log_stepintLoss is printed when epoch % log_step == 0. Must be at least 1.

Raises ValueError when the data lengths do not match the network shape. See Training for details.

forward

forward(tensor: list[float]) -> list[float]

Runs one sample through the network and returns a new list with output_size floats. Raises ValueError if len(tensor) != input_size.

python
model.forward([0.1, 0.2])   # [0.93]

backward

backward(label: list[float]) -> None

Backpropagates one sample, accumulating gradients. Call forward on the same sample first. Raises ValueError if len(label) != output_size. See Custom loops.

export

export(path: str = "model.mlk") -> None

Writes all weights and biases to a binary file.

load

load(path: str = "model.mlk") -> bool

Reads weights from a file written by export. Returns False and prints a warning if the file does not exist, otherwise True. See Saving and loading.