Skip to content

Instantly share code, notes, and snippets.

@tynanbe
Created February 19, 2024 20:17
Show Gist options
  • Save tynanbe/403f9e5e35ccdf1bf2d0de225ce4ef65 to your computer and use it in GitHub Desktop.
Save tynanbe/403f9e5e35ccdf1bf2d0de225ce4ef65 to your computer and use it in GitHub Desktop.
Euclidean distance with Argamak
Input: Tensor(
Format(Float32),
Space(Axis("Note", 1), Axis("Relevancy", 3)),
[[ 3.0, -5.0, 4.0]],
)
Notes: Tensor(
Format(Float32),
Space(Axis("Note", 3), Axis("Relevancy", 3)),
[[ 1.0, 0.0, 3.0],
[ 4.0, 4.0, 2.0],
[-1.0, 8.0, 2.0]],
)
Subtract: Tensor(
Format(Float32),
Space(Axis("Note", 3), Axis("Relevancy", 3)),
[[ 2.0, -5.0, 1.0],
[ -1.0, -9.0, 2.0],
[ 4.0, -13.0, 2.0]],
)
Square: Tensor(
Format(Float32),
Space(Axis("Note", 3), Axis("Relevancy", 3)),
[[ 4.0, 25.0, 1.0],
[ 1.0, 81.0, 4.0],
[ 16.0, 1.69e+2, 4.0]],
)
Sum: Tensor(
Format(Float32),
Space(Axis("Note", 3)),
[5.48, 9.27, 13.7],
)
Best Note: Ok([1.0, 0.0, 3.0])
import gleam/io
import gleam/list
import gleam/result
import argamak/axis.{Axis, Infer}
import argamak/space
import argamak/tensor.{type Tensor, InvalidData, SpaceErrors}
pub fn main() {
let input = [3.0, -5.0, 4.0]
let data = [[1.0, 0.0, 3.0], [4.0, 4.0, 2.0], [-1.0, 8.0, 2.0]]
use d2 <- result.try(
space.d2(Infer("Note"), Axis("Relevancy", size: 3))
|> result.map_error(SpaceErrors),
)
use input <- try("Input", tensor.from_floats(input, into: d2))
use notes <- try(
"Notes",
data
|> list.flatten
|> tensor.from_floats(into: d2),
)
use step1 <- try(
"Subtract",
input
|> tensor.subtract(notes),
)
use step2 <- try(
"Square",
step1
|> tensor.power(to_the: tensor.from_float(2.0)),
)
use step3 <- try(
"Sum",
step2
|> tensor.sum(with: fn(a) { axis.name(a) == "Relevancy" })
|> tensor.square_root,
)
use best_index <- result.try(
step3
|> tensor.arg_min(with: fn(a) { axis.name(a) == "Note" })
|> tensor.to_int,
)
io.print("\nBest Note: ")
data
|> list.at(get: best_index)
|> result.replace_error(InvalidData)
|> io.debug
}
fn try(
title: String,
result: Result(Tensor(a), e),
then: fn(Tensor(a)) -> Result(b, e),
) -> Result(b, e) {
let debug = case title {
"" -> fn(x) { x }
title -> fn(x) {
io.print("\n" <> title <> ": ")
tensor.debug(x)
}
}
use x <- result.try(result)
x
|> debug
|> then
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment