Spellbook: How to do a multilayer perceptron
import arraymancer
let ctx = newContext Tensor[float32]
let bsz = 32
let x_train_bool = randomTensor([bsz * 100, 2], 2).astype(bool)
let y_bool = x_train_bool[_,0] xor x_train_bool[_,1]
let x_train = ctx.variable(x_train_bool.astype(float32), requires_grad = true)
let y = y_bool.astype(float32)
let layer_3neurons = ctx.variable(
randomTensor(3, 2, 2.0f) -. 1.0f,
requires_grad = true
)
let classifier_layer = ctx.variable(
randomTensor(1, 3, 2.0f) -. 1.0f,
requires_grad = true
)
let optim = newSGD[float32](
layer_3neurons, classifier_layer, 0.01f
)
for epoch in 0..5:
for batch_id in 0..<100:
let offset = batch_id * 32
let x = x_train[offset ..< offset + 32, _]
let target = y[offset ..< offset + 32, _]
let n1 = relu linear(x, layer_3neurons)
let n2 = linear(n1, classifier_layer)
let loss = n2.sigmoid_cross_entropy(target)
echo "Epoch is:" & $epoch
echo "Batch id:" & $batch_id
echo "Loss is:" & $loss.value
loss.backprop()
optim.update()
Made with Nim. Generated: 2024-05-12 14:01:32 UTC