| 1 |
-- Simple kann test (xor function vs 2 layer MLP) |
| 2 |
|
| 3 |
context("Kann test", function() |
| 4 |
local kann = require "rspamd_kann" |
| 5 |
local k |
| 6 |
local inputs = { |
| 7 |
{0, 0}, |
| 8 |
{0, 1}, |
| 9 |
{1, 0}, |
| 10 |
{1, 1} |
| 11 |
} |
| 12 |
|
| 13 |
local outputs = { |
| 14 |
{0}, |
| 15 |
{1}, |
| 16 |
{1}, |
| 17 |
{0} |
| 18 |
} |
| 19 |
|
| 20 |
local t = kann.layer.input(2) |
| 21 |
t = kann.transform.relu(t) |
| 22 |
t = kann.transform.tanh(kann.layer.dense(t, 2)); |
| 23 |
t = kann.layer.cost(t, 1, kann.cost.mse) |
| 24 |
k = kann.new.kann(t) |
| 25 |
|
| 26 |
local iters = 500 |
| 27 |
local niter = k:train1(inputs, outputs, { |
| 28 |
lr = 0.01, |
| 29 |
max_epoch = iters, |
| 30 |
mini_size = 80, |
| 31 |
}) |
| 32 |
|
| 33 |
local ser = k:save() |
| 34 |
k = kann.load(ser) |
| 35 |
|
| 36 |
for i,inp in ipairs(inputs) do |
| 37 |
test(string.format("Check XOR MLP %s ^ %s == %s", inp[1], inp[2], outputs[i][1]), |
| 38 |
function() |
| 39 |
local res = math.floor(k:apply1(inp)[1] + 0.5) |
| 40 |
assert_equal(outputs[i][1], res, |
| 41 |
tostring(outputs[i][1]) .. " but test returned " .. tostring(res)) |
| 42 |
end) |
| 43 |
end |
| 44 |
|
| 45 |
|
| 46 |
end) |