Standard library · AI

ai.ml

Classic machine learning: preprocessing, regression, classification, trees, clustering and evaluation.

import ai.ml

This package gives you the classic machine learning algorithms behind an interface much like scikit-learn. The data is a matrix where each row is a sample and each column a feature, and the labels are a one-column matrix. Every model is a struct: build it with its parameters, train it with fit and use it with predict.

Before training, prepare the data with StandardScaler and SimpleImputer and split it with TrainTestSplit; after that, measure the model with metrics such as Accuracy, F1 and R2Score, and pick the parameters with GridSearch. For neural networks see nn; for a trained model from Python, onnx.

Things that trip people up

•

Labels are a one-column matrix of numbers. For classes, use 0, 1, 2 and so on; map class names to numbers yourself and keep the mapping.

•

Nothing stops the program on bad input. fit returns false (and the model's ok stays false) when the shapes do not match, and TrainTestSplit returns empty matrices when x and y have different row counts. Check before you go on.

•

Fit scalers, imputers and encoders on the training rows only, then use the same fitted object on the test rows and on new data.

•

Models and results own matrices. Call free on models and results you are done with in long-running programs.

•

Random parts (splits, forests, k-means starts) take a seed, so a run can be repeated exactly. Change the seed to see how much a result depends on luck.

The usual workflow: split, scale, fit, measure

Every supervised model follows the same steps. Keep part of the data aside with TrainTestSplit, so that the model is judged on samples it never saw. Fit the scaler on the training part only and apply the same scaler to the test part and to any new sample; fitting it on all the data would leak information from the test set. Then fit, predict and measure. ConfusionMatrix shows which classes are mixed up, and PredictProba gives a probability instead of a hard answer.

ml-guide-workflow.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func main:
    mut hours := build(12, 2, "1 4 2 5 2 8 3 6 3 9 4 5 5 7 6 8 7 6 8 7 9 8 10 7")
    mut passed := build(12, 1, "0 0 0 0 1 0 1 1 1 1 1 1")

    mut split := ml.TrainTestSplit(hours, passed, 0.25, 2)
    defer split.Free()
    println "train", matrix.ShapeString(split.x_train), "test", matrix.ShapeString(split.x_test)

    mut scaler := ml.StandardScaler {}
    defer scaler.Free()
    mut train := scaler.FitTransform(split.x_train)
    mut test := scaler.Transform(split.x_test)

    mut model := ml.LogisticRegression { max_iter = 2000 }
    defer model.Free()
    println "trained", model.Fit(train, split.y_train)
    mut pred := model.Predict(test)
    println "accuracy", ml.Accuracy(split.y_test, pred)
    println "confusion", matrix.ToRepr(ml.ConfusionMatrix(split.y_test, pred, 2), 0)

    mut student := scaler.Transform(build(1, 2, "6 6"))
    proba := model.PredictProba(student)
    println "chance to pass", matrix.ToStringPrec(matrix.Full(1, 1, proba.at(0, 1)), 2)
end
Output
train 9x2 test 3x2
trained true
accuracy 1
confusion [2,0; 0,1]
chance to pass 0.95

The fourth argument of TrainTestSplit is a seed, so the split is the same on every run. With twelve samples the test set has three, which is far too few to trust the accuracy; the next sections show better ways to judge a model.

Predict a number: linear regression

When the target is a quantity, such as a price, use a regressor. After fit, coef holds one weight per feature and intercept the base value, so the model can be read directly: here each square meter adds about 2 and each year of age takes away about 1.4. R2Score and RMSE measure the fit; RMSE is in the same unit as the target.

ml-guide-prices.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func f1(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 1)
end

func main:
    mut homes := build(8, 3, "50 1 20 65 2 15 80 2 10 90 3 30 100 3 5 120 4 12 140 4 3 160 5 8")
    mut price := build(8, 1, "105 140 178 172 228 260 312 344")

    mut model := ml.LinearReg {}
    defer model.Free()
    println "fitted", model.Fit(homes, price)
    println "per m2",
        f1(model.coef.at(0, 0)),
        "per room",
        f1(model.coef.at(1, 0)),
        "per year of age",
        f1(model.coef.at(2, 0))
    println "base", f1(model.intercept)

    mut pred := model.Predict(homes)
    println "R2",
        matrix.ToStringPrec(matrix.Full(1, 1, ml.R2Score(price, pred)), 3),
        "RMSE",
        f1(ml.RMSE(price, pred))

    mut offer := model.Predict(build(2, 3, "110 3 10 70 2 25"))
    println "110 m2, 3 rooms, 10 years:", f1(offer.at(0, 0))
    println "70 m2, 2 rooms, 25 years:", f1(offer.at(1, 0))
end
Output
fitted true
per m2 2.0 per room 0.7 per year of age -1.4
base 30.2
R2 1.000 RMSE 1.2
110 m2, 3 rooms, 10 years: 240.3
70 m2, 2 rooms, 25 years: 137.9

Compare models with cross-validation

One split can be lucky or unlucky. StratifiedKFold cuts the data into folds that each keep the share of every class, and CrossValScore trains on all folds but one and tests on the remaining one, for every fold in turn. It takes the model as a function that trains and predicts, so any model fits, and the metric as another function. MeanScore gives the average over the folds.

ml-guide-compare.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func by_knn(train &: matrix.Matrix, labels &: matrix.Matrix, test &: matrix.Matrix): matrix.Matrix:
    mut model := ml.KNNClassifier { k = 3 }
    _ := model.Fit(train, labels)
    pred := model.Predict(test)
    model.Free()
    ret pred
end

func by_tree(train &: matrix.Matrix, labels &: matrix.Matrix, test &: matrix.Matrix): matrix.Matrix:
    mut model := ml.DecisionTree { max_depth = 2 }
    _ := model.Fit(train, labels)
    pred := model.Predict(test)
    model.Free()
    ret pred
end

func by_bayes(train &: matrix.Matrix, labels &: matrix.Matrix, test &: matrix.Matrix): matrix.Matrix:
    mut model := ml.GaussianNB {}
    _ := model.Fit(train, labels)
    pred := model.Predict(test)
    model.Free()
    ret pred
end

func main:
    mut x := build(
        15,
        2,
        "1.4 0.2 1.3 0.2 1.5 0.3 1.7 0.4 1.4 0.3 4.5 1.5 4.0 1.3 4.7 1.4 3.9 1.2 4.4 1.4 5.8 2.2 6.1 2.5 5.1 1.9 5.6 2.1 5.0 1.7"
    )
    mut y := build(15, 1, "0 0 0 0 0 1 1 1 1 1 2 2 2 2 2")
    mut folds := ml.StratifiedKFold(y, 5, 3)
    defer folds.Free()
    accuracy := (a_in: matrix.Matrix, b_in: matrix.Matrix): mut a := a_in mut b := b_in ret ml.Accuracy(a, b) end

    mut knn := ml.CrossValScore((a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret by_knn(a, b, c) end, accuracy, x, y, folds)
    mut tree := ml.CrossValScore((a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret by_tree(a, b, c) end, accuracy, x, y, folds)
    mut bayes := ml.CrossValScore((a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret by_bayes(a, b, c) end, accuracy, x, y, folds)
    println "folds", folds.Count()
    println "k nearest neighbours", ml.MeanScore(knn)
    println "decision tree", ml.MeanScore(tree)
    println "naive Bayes", ml.MeanScore(bayes)
end
Output
folds 5
k nearest neighbours 0.9333333333333332
decision tree 1
naive Bayes 1

Find groups without labels: KMeans

Clustering needs no labels: KMeans puts the samples into k groups of similar values. Scale first, otherwise the feature with the biggest numbers (here spending) decides everything. SilhouetteScore near 1 means well separated groups. The centers are in scaled units, so InverseTransform turns them back into visits and spending that you can describe.

ml-guide-segments.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func main:
    mut customers := build(10, 2, "2 15 3 20 1 10 2 12 12 30 14 35 11 28 4 210 5 250 3 190")

    mut scaler := ml.StandardScaler {}
    defer scaler.Free()
    mut scaled := scaler.FitTransform(customers)

    mut km := ml.KMeans { k = 3, seed = 5 }
    defer km.Free()
    mut labels := km.FitPredict(scaled)
    println "silhouette",
        matrix.ToStringPrec(matrix.Full(1, 1, ml.SilhouetteScore(scaled, labels)), 2)

    mut centers := scaler.InverseTransform(km.centers)
    repeat 3 in c:
        mut members := 0
        repeat labels.rows in i:
            if labels.at(i, 0) as int == c: members++ end
        end
        println "segment",
            c,
            "customers",
            members,
            "visits",
            matrix.ToStringPrec(matrix.Full(1, 1, centers.at(c, 0)), 1),
            "spend",
            matrix.ToStringPrec(matrix.Full(1, 1, centers.at(c, 1)), 1)
    end

    mut fresh := scaler.Transform(build(1, 2, "13 32"))
    println "new customer joins segment", km.Predict(fresh).at(0, 0) as int
end
Output
silhouette 0.83
segment 0 customers 4 visits 2.0 spend 14.3
segment 1 customers 3 visits 4.0 spend 216.7
segment 2 customers 3 visits 12.3 spend 31.0
new customer joins segment 2

Classify text: a small spam filter

Text has to become numbers first. The simplest way is a count matrix: one row per message, one column per word of a vocabulary, holding how often the word appears. MultinomialNB is made for counts like these and trains in one pass. alpha smooths the counts so a word never seen in one class does not rule that class out.

ml-guide-spam.salam
import ai.ml
import matrix

func counts(messages: Vector<str>, vocab: Vector<str>): matrix.Matrix:
    mut m := matrix.Zeros(messages.Len(), vocab.Len())
    each i, text in messages:
        each word in text.Split(" "):
            each j, known in vocab:
                if word == known: m.Set(i, j, m.at(i, j) + 1.0) end
            end
        end
    end
    ret m
end

func main:
    mut vocab := Vector {} as Vector<str>
    defer vocab.Free()
    each w in ["free", "win", "prize", "now", "meeting", "lunch", "report", "tomorrow"]: vocab.Push(w) end

    mut train := Vector {} as Vector<str>
    defer train.Free()
    each t in [
        "win a free prize now", "free prize now", "win now win", "meeting tomorrow",
        "lunch tomorrow", "report for the meeting"
    ]: train.Push(t) end
    mut flags := Vector {} as Vector<f64>
    each f in [1.0, 1.0, 1.0, 0.0, 0.0, 0.0]: flags.Push(f) end
    mut labels := matrix.FromArray(6, 1, flags)

    mut model := ml.MultinomialNB { alpha = 1.0 }
    defer model.Free()
    mut x := counts(train, vocab)
    println "trained", model.Fit(x, labels)

    mut inbox := Vector {} as Vector<str>
    defer inbox.Free()
    each t in ["free lunch tomorrow", "you win a prize", "send the report tomorrow"]: inbox.Push(t) end
    mut pred := model.Predict(counts(inbox, vocab))
    each i, text in inbox:
        mut verdict := "inbox"
        if pred.at(i, 0) == 1.0: verdict = "spam" end
        println verdict, "<-", text
    end
end
Output
trained true
inbox <- free lunch tomorrow
spam <- you win a prize
inbox <- send the report tomorrow

TaskStart withMeasure with Predict a numberLinearRegR2Score, RMSE Yes or no, with a probabilityLogisticRegressionAccuracy, F1, ConfusionMatrix Several classes, small dataKNNClassifier, DecisionTree, GaussianNBCrossValScore Tabular data, best accuracyRandomForest, GradientBoostingCrossValScore, GridSearch Fewer columns, or a picture of the dataPCA, TSNEExplained variance Word countsMultinomialNBAccuracy Groups without labelsKMeansSilhouetteScore

Types

KDTree

#
struct KDTree

A k-d tree for nearest neighbour search.

NameTypeDescription
leaf_sizeint = 16The leaf size of the k-d tree.
xmatrix.MatrixThe data.
idxVector<int>The row permutation.
node_loVector<int>The first row of each node.
node_hiVector<int>The end row of each node.
node_dimVector<int>The split dimension of each node.
node_splitVector<f64>The split value of each node.
node_leftVector<int>The left child.
node_rightVector<int>The right child.
okbool = falseWhether the fit succeeded.
ai-ml-Classify.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func show(name: str, m &: matrix.Matrix):
    println name, matrix.ToRepr(matrix.Chop(m, 0.000001), 3)
end

func f3(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 3)
end

func main:
    mut x := build(8, 2, "1 1 1 2 2 1 2 2 6 6 6 7 7 6 7 7")
    mut y := build(8, 1, "0 0 0 0 1 1 1 1")
    mut test := build(2, 2, "1.5 1.5 6.5 6.5")

    mut knn := ml.KNNClassifier { k = 3, weighted = true, algorithm = ml.KNN_KDTREE }
    println knn.Fit(x, y),
        knn.ok,
        knn.n_classes,
        knn.leaf_size,
        knn.workers,
        matrix.ShapeString(knn.xtrain),
        matrix.ShapeString(knn.ytrain),
        knn.tree.ok
    show("neighbors", knn.Predict(test))
    println matrix.ShapeString(knn.PredictProba(test)), f3(knn.Score(x, y)), ml.KNN_BRUTE
    mut regressor := ml.KNNRegressor { k = 2 }
    println regressor.Fit(x, y),
        regressor.ok,
        regressor.weighted,
        regressor.algorithm,
        regressor.leaf_size,
        regressor.workers,
        matrix.ShapeString(regressor.xtrain),
        matrix.ShapeString(regressor.ytrain),
        regressor.tree.ok
    show("regressor", regressor.Predict(test))
    println f3(regressor.Score(x, y))

    mut gaussian := ml.GaussianNB {}
    println gaussian.Fit(x, y),
        gaussian.ok,
        gaussian.n_classes,
        gaussian.var_smoothing > 0.0,
        matrix.ShapeString(gaussian.means),
        matrix.ShapeString(gaussian.vars),
        matrix.ShapeString(gaussian.log_priors)
    show("gaussian", gaussian.Predict(test))
    println matrix.ShapeString(gaussian.PredictProba(test)), f3(gaussian.Score(x, y))
    mut counts := build(4, 3, "3 0 1 2 0 0 0 3 1 0 2 2")
    mut topic := build(4, 1, "0 0 1 1")
    mut multinomial := ml.MultinomialNB { alpha = 1.0 }
    println multinomial.Fit(counts, topic),
        multinomial.ok,
        multinomial.fit_prior,
        multinomial.n_classes,
        matrix.ShapeString(multinomial.log_prob),
        matrix.ShapeString(multinomial.log_priors)
    show("multinomial", multinomial.Predict(counts))
    println matrix.ShapeString(multinomial.Decision(counts)),
        matrix.ShapeString(multinomial.PredictProba(counts)),
        f3(multinomial.Score(counts, topic))

    mut lda := ml.LDA {}
    println lda.Fit(x, y),
        lda.ok,
        lda.n_classes,
        lda.ridge > 0.0,
        matrix.ShapeString(lda.means),
        matrix.ShapeString(lda.cov),
        matrix.ShapeString(lda.log_priors)
    show("linear", lda.Predict(test))
    println matrix.ShapeString(lda.PredictProba(test)), f3(lda.Score(x, y))
    mut qda := ml.QDA {}
    println qda.Fit(x, y),
        qda.ok,
        qda.n_classes,
        qda.ridge > 0.0,
        matrix.ShapeString(qda.means),
        qda.covs.Len(),
        matrix.ShapeString(qda.log_priors)
    show("quadratic", qda.Predict(test))
    println matrix.ShapeString(qda.PredictProba(test)), f3(qda.Score(x, y))

    mut svm := ml.LinearSVM { c = 1.0 }
    println svm.Fit(x, y),
        svm.ok,
        svm.n_classes,
        svm.max_iter,
        svm.tol > 0.0,
        svm.seed,
        matrix.ShapeString(svm.coef),
        matrix.ShapeString(svm.intercept)
    show("linear svm", svm.Predict(test))
    println matrix.ShapeString(svm.Decision(test)), f3(svm.Score(x, y))
    mut rbf := ml.SVC { kernel = ml.KERNEL_RBF, c = 10.0, gamma = 0.5 }
    println rbf.Fit(x, y),
        rbf.ok,
        rbf.n_classes,
        rbf.NSupport() > 0,
        rbf.degree,
        rbf.coef0,
        rbf.max_passes,
        rbf.tol > 0.0,
        rbf.seed
    println matrix.ShapeString(rbf.support),
        matrix.ShapeString(rbf.dual),
        matrix.ShapeString(rbf.bias)
    show("rbf kernel", rbf.Predict(test))
    println matrix.ShapeString(rbf.Decision(test)),
        f3(rbf.Score(x, y)),
        ml.KERNEL_LINEAR,
        ml.KERNEL_POLY

    mut truth := build(6, 1, "0 0 1 1 1 0")
    mut pred := build(6, 1, "0 1 1 1 0 0")
    mut score := build(6, 1, "0.1 0.6 0.8 0.9 0.4 0.2")
    println f3(ml.Accuracy(truth, pred)),
        f3(ml.Precision(truth, pred, 1.0)),
        f3(ml.Recall(truth, pred, 1.0)),
        f3(ml.F1(truth, pred, 1.0)),
        f3(ml.MacroF1(truth, pred, 2))
    show("confusion", ml.ConfusionMatrix(truth, pred, 2))
    println f3(ml.RocAuc(truth, score)),
        f3(ml.AveragePrecision(truth, score)),
        f3(ml.BalancedAccuracy(truth, pred)),
        f3(ml.MatthewsCorrCoef(truth, pred)),
        f3(ml.CohenKappa(truth, pred))
    println matrix.ShapeString(ml.RocCurve(truth, score)),
        matrix.ShapeString(ml.PrecisionRecallCurve(truth, score))
    mut proba := build(6, 2, "0.9 0.1 0.4 0.6 0.2 0.8 0.1 0.9 0.6 0.4 0.8 0.2")
    println f3(ml.LogLoss(truth, proba))
    knn.Free()
    regressor.Free()
    gaussian.Free()
    multinomial.Free()
    lda.Free()
    qda.Free()
    svm.Free()
    rbf.Free()
end
Output
true true 2 16 0 8x2 8x1 true
neighbors [0.000; 1.000]
2x2 1.000 0
true true false 0 16 0 8x2 8x1 false
regressor [0.000; 1.000]
1.000
true true 2 true 2x2 2x2 2x1
gaussian [0.000; 1.000]
2x2 1.000
true true true 2 2x3 2x1
multinomial [0.000; 0.000; 1.000; 1.000]
4x2 4x2 1.000
true true 2 true 2x2 2x2 2x1
linear [0.000; 1.000]
2x2 1.000
true true 2 true 2x2 2 2x1
quadratic [0.000; 1.000]
2x2 1.000
true true 2 1000 true 42 2x1 1x1
linear svm [0.000; 1.000]
2x1 1.000
true true 2 true 3 1 20 true 42
8x2 8x1 1x1
rbf kernel [0.000; 1.000]
2x1 1.000 0 2
0.667 0.667 0.667 0.667 0.667
confusion [2.000,1.000; 1.000,2.000]
0.889 0.917 0.667 0.333 0.333
7x3 6x3
0.415

Build

#
func Build(x &: matrix.Matrix): bool

Builds the tree from the data.

The example for this item is shown with the ones above: ai-ml-Classify.salam

NodeCount

#
func NodeCount(): int

The number of nodes.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Query

#
func Query(q &: matrix.Matrix, qi: int, k: int, dist_out &: Vector<f64>): Vector<int>

The k nearest neighbours of row qi, with their distances.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

LinearReg

#
struct LinearReg

Linear regression by least squares.

NameTypeDescription
fit_interceptbool = trueWhether to fit an intercept too.
coefmatrix.MatrixThe coefficients.
interceptf64 = 0The intercept.
okbool = falseWhether the fit succeeded.
ai-ml-Linear.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func show(name: str, m &: matrix.Matrix):
    println name, matrix.ToRepr(matrix.Chop(m, 0.000001), 3)
end

func f3(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 3)
end

func main:
    mut x := build(5, 2, "1 0 2 1 3 0 4 1 5 0")
    mut y := build(5, 1, "3 6 7 10 11")
    mut linear := ml.LinearReg {}
    println linear.Fit(x, y), linear.ok, linear.fit_intercept, f3(linear.intercept)
    show("coefficients", linear.coef)
    mut pred := linear.Predict(x)
    show("prediction", pred)
    println f3(linear.Score(x, y)), f3(ml.R2Score(y, pred))
    mut guess := build(5, 1, "3.5 5.5 7 10 12")
    println f3(ml.MSE(y, guess)), f3(ml.MAE(y, guess)), f3(ml.RMSE(y, guess))
    println f3(ml.MedianAbsoluteError(y, guess)),
        f3(ml.MAPE(y, guess)),
        f3(ml.ExplainedVariance(y, guess))

    mut ridge := ml.Ridge { alpha = 1.0 }
    println ridge.Fit(x, y), ridge.ok, ridge.alpha, ridge.fit_intercept, f3(ridge.intercept)
    show("ridge", ridge.coef)
    println ridge.Score(x, y) > 0.9, matrix.ShapeString(ridge.Predict(x))
    mut lasso := ml.Lasso { alpha = 0.1 }
    println lasso.Fit(x, y),
        lasso.ok,
        lasso.alpha,
        lasso.l1_ratio,
        lasso.fit_intercept,
        lasso.max_iter,
        lasso.tol > 0.0,
        lasso.n_iter > 0,
        lasso.intercept > 0.0
    show("lasso", lasso.coef)
    println lasso.Score(x, y) > 0.9, matrix.ShapeString(lasso.Predict(x))
    mut elastic := ml.NewElasticNet(0.1, 0.5)
    println elastic.Fit(x, y), elastic.l1_ratio

    mut hours := build(6, 1, "1 2 3 4 5 6")
    mut passed := build(6, 1, "0 0 0 1 1 1")
    mut logistic := ml.LogisticRegression { alpha = 0.01, max_iter = 2000 }
    println logistic.Fit(hours, passed),
        logistic.ok,
        logistic.n_classes,
        logistic.fit_intercept,
        logistic.n_iter > 0,
        logistic.tol > 0.0
    println matrix.ShapeString(logistic.coef), matrix.ShapeString(logistic.intercept)
    show("prediction", logistic.Predict(hours))
    mut proba := logistic.PredictProba(build(2, 1, "1 6"))
    println proba.at(0, 1) < 0.5, proba.at(1, 1) > 0.5, f3(logistic.Score(hours, passed))
    linear.Free()
    ridge.Free()
    lasso.Free()
    elastic.Free()
    logistic.Free()
end
Output
true true true 1.000
coefficients [2.000; 1.000]
prediction [3.000; 6.000; 7.000; 10.000; 11.000]
1.000 1.000
0.300 0.400 0.548
0.500 0.068 0.968
true true 1 true 1.727
ridge [1.818; 0.545]
true 5x1
true true 0.1 1 true 1000 true true true
lasso [1.950; 0.583]
true 5x1
true 0.5
true true 2 true true true
1x2 1x2
prediction [0.000; 0.000; 0.000; 1.000; 1.000; 1.000]
true true 1.000

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Ridge

#
struct Ridge

Ridge regression: linear with an L2 penalty.

NameTypeDescription
alphaf64 = 1The regularisation strength.
fit_interceptbool = trueWhether to fit an intercept too.
coefmatrix.MatrixThe coefficients.
interceptf64 = 0The intercept.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Lasso

#
struct Lasso

Lasso: linear with an L1 penalty that drives unimportant coefficients to zero; with an l1_ratio below one it is an elastic net.

NameTypeDescription
alphaf64 = 1The regularisation strength.
l1_ratiof64 = 1The L1 share of the penalty; one means lasso.
fit_interceptbool = trueWhether to fit an intercept too.
max_iterint = 1000The maximum number of iterations.
tolf64 = 0.0001The convergence tolerance.
coefmatrix.MatrixThe coefficients.
interceptf64 = 0The intercept.
n_iterint = 0The number of iterations run.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Linear.salam

LogisticRegression

#
struct LogisticRegression

Logistic regression for classification, with any number of classes.

NameTypeDescription
alphaf64 = 0.0001The regularisation strength.
fit_interceptbool = trueWhether to fit an intercept too.
max_iterint = 500The maximum number of iterations.
tolf64 = 1e-06The convergence tolerance.
coefmatrix.MatrixThe coefficients.
interceptmatrix.MatrixThe intercept.
n_classesint = 0The number of classes.
n_iterint = 0The number of iterations run.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Linear.salam

HistTree

#
struct HistTree

One histogram boosting tree.

NameTypeDescription
featureVector<int>The split feature of each node.
thresholdVector<f64>The split threshold of each node.
leftVector<int>The left child of each node.
rightVector<int>The right child of each node.
valueVector<f64>The value or probabilities of the leaves.
ai-ml-Trees.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func show(name: str, m &: matrix.Matrix):
    println name, matrix.ToRepr(matrix.Chop(m, 0.000001), 3)
end

func f3(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 3)
end

func ints(v: Vector<int>): str:
    mut text := "["
    repeat v.Len() in i:
        if i > 0:
            text += " "
        end
        text += "" + v.Get(i)
    end
    ret text + "]"
end

func main:
    mut x := build(8, 2, "1 1 1 2 2 1 2 2 6 6 6 7 7 6 7 7")
    mut y := build(8, 1, "0 0 0 0 1 1 1 1")
    mut test := build(2, 2, "1.5 1.5 6.5 6.5")

    mut tree := ml.DecisionTree { criterion = ml.TREE_GINI, max_depth = 3 }
    println tree.Fit(x, y),
        tree.ok,
        tree.n_classes,
        tree.IsRegression(),
        tree.NodeCount(),
        tree.ApplyRow(test, 0) >= 0
    println tree.min_samples_split,
        tree.min_samples_leaf,
        tree.max_features,
        tree.seed,
        tree.n_classes_hint,
        tree.feature.Len(),
        tree.threshold.Len(),
        tree.left.Len(),
        tree.right.Len(),
        matrix.ShapeString(tree.value)
    show("tree", tree.Predict(test))
    println matrix.ShapeString(tree.PredictProba(test)), f3(tree.Score(x, y))
    mut regression := ml.DecisionTree { criterion = ml.TREE_MSE }
    println regression.Fit(x, build(8, 1, "1 1 1 1 5 5 5 5")),
        regression.IsRegression(),
        ml.TREE_ENTROPY

    mut forest := ml.RandomForest { n_trees = 20, max_depth = 4, seed = 3 }
    println forest.Fit(x, y),
        forest.ok,
        forest.n_classes,
        forest.trees.Len(),
        forest.IsRegression(),
        forest.criterion,
        forest.min_samples_leaf,
        forest.max_features,
        forest.bootstrap,
        forest.workers
    show("forest", forest.Predict(test))
    println matrix.ShapeString(forest.PredictProba(test)), f3(forest.Score(x, y))
    forest.FreeTrees()

    mut ada := ml.AdaBoost { n_estimators = 10 }
    println ada.Fit(x, y),
        ada.ok,
        ada.n_classes,
        ada.trees.Len() > 0,
        ada.alphas.Len() > 0,
        ada.max_depth,
        ada.learning_rate,
        ada.seed
    show("adaboost", ada.Predict(test))
    println f3(ada.Score(x, y))
    ada.FreeAll()

    mut boost := ml.GradientBoosting { n_estimators = 20, learning_rate = 0.3, max_depth = 2 }
    println boost.Fit(x, y),
        boost.ok,
        boost.n_classes,
        boost.trees.Len(),
        boost.min_samples_leaf,
        boost.regression,
        matrix.ShapeString(boost.base)
    show("gradient boosting", boost.Predict(test))
    println matrix.ShapeString(boost.Decision(test)),
        matrix.ShapeString(boost.PredictProba(test)),
        f3(boost.Score(x, y))
    boost.FreeAll()

    mut hist := ml.HistGradientBoosting { n_estimators = 20, min_samples_leaf = 1, max_bins = 16 }
    println hist.Fit(x, y),
        hist.ok,
        hist.n_classes,
        hist.trees.Len() > 0,
        hist.max_depth,
        hist.l2,
        hist.learning_rate,
        hist.regression,
        hist.edges.Len() > 0,
        hist.edges_start.Len(),
        hist.base.Len()
    show("histogram", hist.Predict(test))
    println matrix.ShapeString(hist.Decision(test)),
        matrix.ShapeString(hist.PredictProba(test)),
        f3(hist.Score(x, y))
    mut first := hist.trees.Get(0)
    println first.feature.Len() > 0,
        first.threshold.Len() > 0,
        first.left.Len() > 0,
        first.right.Len() > 0,
        first.value.Len() > 0
    hist.FreeAll()

    mut kd := ml.NewKDTree(x, 2)
    mut dists := Vector {} as Vector<f64>
    println kd.ok, kd.leaf_size, kd.NodeCount() > 0, ints(
        kd.Query(test, 1, 2, dists)
    ), f3(dists.Get(0))
    println matrix.ShapeString(kd.x),
        kd.idx.Len(),
        kd.node_lo.Len() > 0,
        kd.node_hi.Len() > 0,
        kd.node_dim.Len() > 0,
        kd.node_split.Len() > 0,
        kd.node_left.Len() > 0,
        kd.node_right.Len() > 0
    mut empty := ml.KDTree {}
    println empty.Build(x), empty.NodeCount() > 0
    kd.Free()
    empty.Free()
    tree.Free()
    regression.Free()
end
Output
true true 2 false 3 true
2 1 0 42 0 3 3 3 3 3x2
tree [0.000; 1.000]
2x2 1.000
true true 1
true true 2 20 false 0 1 0 true 0
forest [0.000; 1.000]
2x2 1.000
true true 2 true true 1 1 42
adaboost [0.000; 1.000]
1.000
true true 2 40 1 false 1x2
gradient boosting [0.000; 1.000]
2x2 2x2 1.000
true true 2 true 6 1 0.1 false true 3 2
histogram [0.000; 1.000]
2x2 2x2 1.000
true true true true true
true 2 true [4 5] 0.500
8x2 8 true true true true true true
true true

ApplyRow

#
func ApplyRow(x &: matrix.Matrix, i: int): f64

The leaf the row ends up in.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

HistGradientBoosting

#
struct HistGradientBoosting

Histogram gradient boosting, fast on large data, like LightGBM.

NameTypeDescription
n_estimatorsint = 100The number of estimators.
learning_ratef64 = 0.1The learning rate.
max_depthint = 6The maximum tree depth.
max_binsint = 255The maximum number of bins per feature.
min_samples_leafint = 20The minimum number of samples in a leaf.
l2f64 = 1L2 regularisation of the leaves.
regressionbool = falseRegression instead of classification.
edgesVector<f64>The bin edges.
edges_startVector<int>Where the edges of each feature start.
baseVector<f64>The initial prediction.
treesVector<HistTree>The trees.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Decision

#
func Decision(x &: matrix.Matrix): matrix.Matrix

The decision score before it becomes a class.

The example for this item is shown with the ones above: ai-ml-Trees.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Trees.salam

FreeAll

#
func FreeAll()

Frees all the trees.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

LDA

#
struct LDA

Linear discriminant analysis.

NameTypeDescription
ridgef64 = 1e-06Covariance regularisation, for stability.
meansmatrix.MatrixThe mean of each class.
covmatrix.MatrixThe shared covariance.
log_priorsmatrix.MatrixThe log prior probability of each class.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Classify.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

QDA

#
struct QDA

Quadratic discriminant analysis, with a separate covariance for each class.

NameTypeDescription
ridgef64 = 1e-06Covariance regularisation, for stability.
meansmatrix.MatrixThe mean of each class.
covsVector<matrix.Matrix>The covariance of each class.
log_priorsmatrix.MatrixThe log prior probability of each class.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

KMeans

#
struct KMeans

k-means clustering.

NameTypeDescription
kint = 8The number of neighbours or clusters.
max_iterint = 300The maximum number of iterations.
tolf64 = 0.0001The convergence tolerance.
n_initint = 3How many runs with different starts; the best one is kept.
seedi64 = 42The random seed, for a repeatable result.
workersint = 0The number of threads; zero means automatic.
centersmatrix.MatrixThe cluster centres.
inertiaf64 = 0The sum of squared distances to the centres.
n_iterint = 0The number of iterations run.
okbool = falseWhether the fit succeeded.
ai-ml-Cluster.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func f3(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 3)
end

func main:
    mut x := build(8, 2, "1 1 1 2 2 1 2 2 8 8 8 9 9 8 9 9")
    mut truth := build(8, 1, "0 0 0 0 1 1 1 1")

    mut km := ml.KMeans { k = 2, seed = 1 }
    mut labels := km.FitPredict(x)
    println km.ok,
        km.n_iter > 0,
        f3(km.inertia),
        matrix.ShapeString(km.centers),
        km.max_iter,
        km.tol > 0.0,
        km.n_init,
        km.workers
    println labels.at(0, 0) != labels.at(4, 0),
        f3(ml.AdjustedRandIndex(labels, truth)),
        f3(ml.SilhouetteScore(x, labels))
    println km.Fit(x), matrix.ShapeString(km.Predict(x))
    mut mini := ml.MiniBatchKMeans {
        k = 2,
        batch_size = 4,
        max_iter = 50,
        seed = 2
    }
    println mini.Fit(x),
        mini.ok,
        matrix.ShapeString(mini.centers),
        f3(ml.AdjustedRandIndex(mini.FitPredict(x), truth)),
        matrix.ShapeString(mini.Predict(x))

    mut density := ml.DBSCAN { eps = 1.5, min_samples = 3 }
    mut clusters := density.FitPredict(x)
    println density.ok,
        density.n_clusters,
        matrix.ShapeString(density.labels),
        f3(ml.AdjustedRandIndex(clusters, truth)),
        density.Fit(x)

    mut agg := ml.Agglomerative { n_clusters = 2, linkage = ml.LINK_AVERAGE }
    println f3(ml.AdjustedRandIndex(agg.FitPredict(x), truth)),
        agg.ok,
        matrix.ShapeString(agg.labels),
        agg.Fit(x)
    println ml.LINK_SINGLE, ml.LINK_COMPLETE

    mut mixture := ml.GaussianMixture { k = 2, seed = 3 }
    println f3(ml.AdjustedRandIndex(mixture.FitPredict(x), truth)),
        mixture.ok,
        mixture.n_iter > 0,
        mixture.log_likelihood != 0.0,
        mixture.max_iter,
        mixture.tol > 0.0,
        mixture.var_floor > 0.0
    println matrix.ShapeString(mixture.means),
        matrix.ShapeString(mixture.vars),
        matrix.ShapeString(mixture.weights),
        mixture.Fit(x)
    println matrix.ShapeString(mixture.Predict(x)), matrix.ShapeString(mixture.PredictProba(x))

    mut tsne := ml.TSNE {
        n_components = 2,
        perplexity = 2.0,
        n_iter = 250,
        seed = 4
    }
    mut embedded := tsne.FitTransform(x)
    println tsne.ok,
        matrix.ShapeString(embedded),
        matrix.ShapeString(tsne.embedding),
        tsne.kl >= 0.0,
        tsne.learning_rate,
        tsne.early_exaggeration
    km.Free()
    mini.Free()
    density.Free()
    agg.Free()
    mixture.Free()
    tsne.Free()
end
Output
true true 4.000 2x2 300 true 3 0
true 1.000 0.885
true 8x1
true true 2x2 1.000 8x1
true 2 8x1 1.000 true
1.000 true 8x1 true
0 1
1.000 true true true 100 true true
2x2 2x2 2x1 true
8x1 8x2
true 8x2 8x2 true 0 12

Fit

#
func Fit(x &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

FitPredict

#
func FitPredict(x &: matrix.Matrix): matrix.Matrix

Fits and returns the cluster label of each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

DBSCAN

#
struct DBSCAN

Density clustering; it finds the number of clusters itself and sets the noise apart.

NameTypeDescription
epsf64 = 0.5The neighbourhood radius.
min_samplesint = 5The minimum number of neighbours for a core point.
labelsmatrix.MatrixThe cluster label of each row; -1 means noise.
n_clustersint = 0The number of clusters found.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

FitPredict

#
func FitPredict(x &: matrix.Matrix): matrix.Matrix

Fits and returns the cluster label of each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

LinearSVM

#
struct LinearSVM

A linear support vector machine.

NameTypeDescription
cf64 = 1The error penalty; larger means a harder margin.
max_iterint = 1000The maximum number of iterations.
tolf64 = 0.0001The convergence tolerance.
seedi64 = 42The random seed, for a repeatable result.
coefmatrix.MatrixThe coefficients.
interceptmatrix.MatrixThe intercept.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Decision

#
func Decision(x &: matrix.Matrix): matrix.Matrix

The decision score before it becomes a class.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

SVC

#
struct SVC

A kernel support vector machine.

NameTypeDescription
cf64 = 1The error penalty; larger means a harder margin.
kernelintThe kernel, one of the KERNEL_... constants.
gammaf64 = 0The RBF kernel parameter; zero means automatic.
degreeint = 3The degree of the polynomial kernel.
coef0f64 = 1The constant term of the polynomial kernel.
max_passesint = 20The maximum number of SMO passes with no change.
tolf64 = 0.001The convergence tolerance.
seedi64 = 42The random seed, for a repeatable result.
supportmatrix.MatrixThe support vectors.
dualmatrix.MatrixThe dual coefficients.
biasmatrix.MatrixThe bias.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Decision

#
func Decision(x &: matrix.Matrix): matrix.Matrix

The decision score before it becomes a class.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

NSupport

#
func NSupport(): int

The number of support vectors.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

AdaBoost

#
struct AdaBoost

AdaBoost with shallow trees.

NameTypeDescription
n_estimatorsint = 50The number of estimators.
max_depthint = 1The maximum tree depth.
learning_ratef64 = 1The learning rate.
seedi64 = 42The random seed, for a repeatable result.
treesVector<DecisionTree>The trees.
alphasVector<f64>The weight of each tree.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Trees.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Trees.salam

FreeAll

#
func FreeAll()

Frees all the trees.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

GradientBoosting

#
struct GradientBoosting

Gradient boosting with trees.

NameTypeDescription
n_estimatorsint = 100The number of estimators.
learning_ratef64 = 0.1The learning rate.
max_depthint = 3The maximum tree depth.
min_samples_leafint = 1The minimum number of samples in a leaf.
regressionbool = falseRegression instead of classification.
treesVector<DecisionTree>The trees.
basematrix.MatrixThe initial prediction.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Decision

#
func Decision(x &: matrix.Matrix): matrix.Matrix

The decision score before it becomes a class.

The example for this item is shown with the ones above: ai-ml-Trees.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

FreeAll

#
func FreeAll()

Frees all the trees.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Split

#
struct Split

Data after a split.

NameTypeDescription
x_trainmatrix.MatrixThe training features.
x_testmatrix.MatrixThe test features.
y_trainmatrix.MatrixThe training labels.
y_testmatrix.MatrixThe test labels.
ai-ml-Prep.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func show(name: str, m &: matrix.Matrix):
    println name, matrix.ToRepr(matrix.Chop(m, 0.000001), 3)
end

func ints(v: Vector<int>): str:
    mut text := "["
    repeat v.Len() in i:
        if i > 0:
            text += " "
        end
        text += "" + v.Get(i)
    end
    ret text + "]"
end

func main:
    mut data := build(4, 2, "1 10 2 20 3 30 4 40")
    mut standard := ml.StandardScaler {}
    mut scaled := standard.FitTransform(data)
    show("standard", scaled)
    show("mean", standard.mean)
    println standard.ok, standard.with_mean, standard.with_std, matrix.ShapeString(standard.std)
    show("back", standard.InverseTransform(scaled))
    mut minmax := ml.MinMaxScaler { lo = 0.0, hi = 1.0 }
    println minmax.Fit(data)
    show("minmax", minmax.Transform(data))
    show("back", minmax.InverseTransform(minmax.FitTransform(data)))
    println minmax.ok, matrix.ShapeString(minmax.data_min), matrix.ShapeString(minmax.data_range)
    println standard.Fit(data), matrix.ShapeString(standard.Transform(data))

    mut labels := Vector {} as Vector<str>
    each label in ["cat", "dog", "cat", "fish"]:
        labels.Push(label)
    end
    mut encoder := ml.LabelEncoder {}
    mut codes := encoder.FitTransform(labels)
    show("label", codes)
    println encoder.ok,
        encoder.classes.Len(),
        encoder.IndexOf("dog"),
        encoder.InverseTransform(codes).Get(3),
        encoder.Fit(labels),
        matrix.ShapeString(encoder.Transform(labels))
    mut onehot := ml.OneHotEncoder {}
    mut hot := onehot.FitTransform(codes)
    show("onehot", hot)
    show("back", onehot.InverseTransform(hot))
    println onehot.ok,
        onehot.n_classes,
        onehot.Fit(codes),
        matrix.ShapeString(onehot.Transform(codes))
    println ints(ml.LabelsToInts(codes)), ml.CountClasses(codes)

    mut missing := build(3, 2, "1 4 nan 6 3 nan")
    mut imputer := ml.SimpleImputer { strategy = ml.IMPUTE_MEAN }
    show("mean", imputer.FitTransform(missing))
    mut imputer2 := ml.SimpleImputer { strategy = ml.IMPUTE_CONSTANT, fill = -1.0 }
    println imputer2.Fit(missing), imputer2.ok, matrix.ShapeString(imputer2.stats)
    show("constant", imputer2.Transform(missing))
    println ml.IMPUTE_MEDIAN
    mut poly := ml.PolynomialFeatures { degree = 2, include_bias = true }
    show("polynomial", poly.Transform(build(1, 2, "2 3")))

    mut linear := build(4, 2, "1 2 2 4 3 6 4 8")
    mut pca := ml.PCA { n_components = 1 }
    println pca.Fit(linear),
        pca.ok,
        matrix.ShapeString(pca.components),
        matrix.ShapeString(pca.mean)
    show("variance", pca.explained_ratio)
    println matrix.ShapeString(pca.explained_variance),
        matrix.ShapeString(pca.Transform(linear)),
        matrix.ShapeString(pca.FitTransform(linear))
    show("back", pca.InverseTransform(pca.Transform(linear)))
    mut svd := ml.TruncatedSVD { n_components = 1 }
    println svd.Fit(linear),
        svd.ok,
        matrix.ShapeString(svd.components),
        matrix.ShapeString(svd.singular_values),
        matrix.ShapeString(svd.explained_variance),
        matrix.ShapeString(svd.explained_ratio)
    println matrix.ShapeString(svd.Transform(linear)), matrix.ShapeString(svd.FitTransform(linear))

    mut x := build(6, 1, "1 2 3 4 5 6")
    mut y := build(6, 1, "0 0 0 1 1 1")
    mut split := ml.TrainTestSplit(x, y, 0.5, 7)
    println matrix.ShapeString(split.x_train),
        matrix.ShapeString(split.x_test),
        matrix.ShapeString(split.y_train),
        matrix.ShapeString(split.y_test)
    mut folds := ml.KFold(6, 3, false, 0)
    println folds.Count(), ints(folds.test.Get(0)), ints(folds.train.Get(0))
    mut stratified := ml.StratifiedKFold(y, 3, 1)
    println stratified.Count(), stratified.test.Get(0).Len()
    println ml.ML_TOL > 0.0
    standard.Free()
    minmax.Free()
    encoder.Free()
    imputer.Free()
    pca.Free()
    svd.Free()
end
Output
standard [-1.342,-1.342; -0.447,-0.447; 0.447,0.447; 1.342,1.342]
mean [2.500,25.000]
true true true 1x2
back [1.000,10.000; 2.000,20.000; 3.000,30.000; 4.000,40.000]
true
minmax [0.000,0.000; 0.333,0.333; 0.667,0.667; 1.000,1.000]
back [1.000,10.000; 2.000,20.000; 3.000,30.000; 4.000,40.000]
true 1x2 1x2
true 4x2
label [0.000; 1.000; 0.000; 2.000]
true 3 1 fish true 4x1
onehot [1.000,0.000,0.000; 0.000,1.000,0.000; 1.000,0.000,0.000; 0.000,0.000,1.000]
back [0.000; 1.000; 0.000; 2.000]
true 3 true 4x3
[0 1 0 2] 3
mean [1.000,4.000; 2.000,6.000; 3.000,5.000]
true true 1x2
constant [1.000,4.000; -1.000,6.000; 3.000,-1.000]
1
polynomial [1.000,2.000,3.000,4.000,6.000,9.000]
true true 2x1 1x2
variance [1.000]
1x1 4x1 4x1
back [1.000,2.000; 2.000,4.000; 3.000,6.000; 4.000,8.000]
true true 2x1 1x1 1x1 1x1
4x1 4x1
3x1 3x1 3x1 3x1
3 [0 1] [2 3 4 5]
3 2
true

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Folds

#
struct Folds

Cross-validation folds.

NameTypeDescription
trainVector<Vector<int>>The training row numbers of each fold.
testVector<Vector<int>>The test row numbers of each fold.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Count

#
func Count(): int

The number of folds.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

GridResult

#
struct GridResult

The result of a grid search.

NameTypeDescription
scoresVector<f64>The mean score of each candidate.
bestint = -1The number of the best one.
best_scoref64 = 0The best score.
ai-ml-Select.salam
import ai.ml
import matrix

func build(rows: int, cols: int, numbers: str): matrix.Matrix:
    mut data := Vector {} as Vector<f64>
    each number in numbers.Split(" "):
        data.Push(number.ToFloat())
    end
    ret matrix.FromArray(rows, cols, data)
end

func f3(number: f64): str:
    ret matrix.ToStringPrec(matrix.Full(1, 1, number), 3)
end

func neighbors(k: int, train &: matrix.Matrix, labels &: matrix.Matrix, test &: matrix.Matrix): matrix.Matrix:
    mut model := ml.KNNClassifier { k = k }
    _ := model.Fit(train, labels)
    pred := model.Predict(test)
    model.Free()
    ret pred
end

func main:
    mut x := build(8, 2, "1 1 1 2 2 1 2 2 6 6 6 7 7 6 7 7")
    mut y := build(8, 1, "0 0 0 0 1 1 1 1")
    mut folds := ml.StratifiedKFold(y, 4, 1)
    mut scores := ml.CrossValScore((a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret neighbors(1, a, b, c) end, (a_in: matrix.Matrix, b_in: matrix.Matrix): mut a := a_in mut b := b_in ret ml.Accuracy(a, b) end, x, y, folds)
    println scores.Len(), f3(ml.MeanScore(scores))
    mut parallel := ml.CrossValScoreParallel((a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret neighbors(1, a, b, c) end, (a_in: matrix.Matrix, b_in: matrix.Matrix): mut a := a_in mut b := b_in ret ml.Accuracy(a, b) end, x, y, folds, 2)
    println f3(ml.MeanScore(parallel))

    mut candidates := Vector {} as Vector<ml.Candidate>
    candidates.Push(ml.Candidate { name = "k=1", fit = (a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret neighbors(1, a, b, c) end })
    candidates.Push(ml.Candidate { name = "k=3", fit = (a_in: matrix.Matrix, b_in: matrix.Matrix, c_in: matrix.Matrix): mut c := c_in mut a := a_in mut b := b_in ret neighbors(3, a, b, c) end })
    mut result := ml.GridSearch(candidates, (a_in: matrix.Matrix, b_in: matrix.Matrix): mut a := a_in mut b := b_in ret ml.Accuracy(a, b) end, x, y, folds, 1)
    println result.scores.Len(),
        result.best >= 0,
        f3(result.best_score),
        candidates.Get(result.best).name.Len() > 0
end
Output
4 1.000
1.000
2 true 1.000 true

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Select.salam

Candidate

#
struct Candidate

One candidate in a grid search.

NameTypeDescription
namestr = ""The name.
fitfunc(matrix.Matrix, matrix.Matrix, matrix.Matrix): matrix.MatrixA function that takes the training and test data and returns a prediction.

The example for this item is shown with the ones above: ai-ml-Select.salam

PCA

#
struct PCA

Principal component analysis, for reducing dimensions.

NameTypeDescription
n_componentsint = 0The number of components.
componentsmatrix.MatrixThe components.
meanmatrix.MatrixThe column means.
explained_variancematrix.MatrixThe variance of each component.
explained_ratiomatrix.MatrixThe share of the variance each component explains.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(z &: matrix.Matrix): matrix.Matrix

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

TruncatedSVD

#
struct TruncatedSVD

Truncated singular value decomposition: like PCA without subtracting the mean, for sparse data.

NameTypeDescription
n_componentsint = 2The number of components.
componentsmatrix.MatrixThe components.
singular_valuesmatrix.MatrixThe singular values.
explained_variancematrix.MatrixThe variance of each component.
explained_ratiomatrix.MatrixThe share of the variance each component explains.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(z &: matrix.Matrix): matrix.Matrix

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

GaussianNB

#
struct GaussianNB

Gaussian naive Bayes, for continuous features.

NameTypeDescription
var_smoothingf64 = 1e-09Added to the variances for stability.
meansmatrix.MatrixThe mean of each class.
varsmatrix.MatrixThe variances.
log_priorsmatrix.MatrixThe log prior probability of each class.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Classify.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

MultinomialNB

#
struct MultinomialNB

Multinomial naive Bayes, for counts such as in text classification.

NameTypeDescription
alphaf64 = 1Laplace smoothing for zero counts.
fit_priorbool = trueWhether to learn the prior probabilities from the data.
log_probmatrix.MatrixThe log probability of each feature in each class.
log_priorsmatrix.MatrixThe log prior probability of each class.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Decision

#
func Decision(x &: matrix.Matrix): matrix.Matrix

The decision score before it becomes a class.

The example for this item is shown with the ones above: ai-ml-Classify.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

TSNE

#
struct TSNE

t-SNE, for showing high-dimensional data in two or three dimensions.

NameTypeDescription
n_componentsint = 2The number of components.
perplexityf64 = 30The perplexity, roughly the number of effective neighbours.
learning_ratef64 = 0The learning rate.
n_iterint = 500The number of iterations run.
early_exaggerationf64 = 12The early exaggeration.
seedi64 = 42The random seed, for a repeatable result.
embeddingmatrix.MatrixThe output points.
klf64 = 0The final KL divergence.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

KNNClassifier

#
struct KNNClassifier

A k nearest neighbours classifier.

NameTypeDescription
kint = 5The number of neighbours or clusters.
weightedbool = falseWeights the neighbours by inverse distance.
algorithmintThe search method, one of the KNN_... constants.
leaf_sizeint = 16The leaf size of the k-d tree.
workersint = 0The number of threads; zero means automatic.
xtrainmatrix.MatrixThe training data.
ytrainmatrix.MatrixThe training labels.
treeKDTreeThe k-d tree.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Classify.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Select.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

KNNRegressor

#
struct KNNRegressor

A k nearest neighbours regressor.

NameTypeDescription
kint = 5The number of neighbours or clusters.
weightedbool = falseWeights the neighbours by inverse distance.
algorithmintThe search method, one of the KNN_... constants.
leaf_sizeint = 16The leaf size of the k-d tree.
workersint = 0The number of threads; zero means automatic.
xtrainmatrix.MatrixThe training data.
ytrainmatrix.MatrixThe training labels.
treeKDTreeThe k-d tree.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Classify.salam

GaussianMixture

#
struct GaussianMixture

A Gaussian mixture model, fitted with EM.

NameTypeDescription
kint = 2The number of neighbours or clusters.
max_iterint = 100The maximum number of iterations.
tolf64 = 0.0001The convergence tolerance.
var_floorf64 = 1e-06The minimum variance.
seedi64 = 42The random seed, for a repeatable result.
meansmatrix.MatrixThe mean of each class.
varsmatrix.MatrixThe variances.
weightsmatrix.MatrixThe weight of each component.
log_likelihoodf64 = 0The log likelihood.
n_iterint = 0The number of iterations run.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

FitPredict

#
func FitPredict(x &: matrix.Matrix): matrix.Matrix

Fits and returns the cluster label of each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Agglomerative

#
struct Agglomerative

Agglomerative hierarchical clustering.

NameTypeDescription
n_clustersint = 2The number of clusters.
linkageintThe linkage method, one of the LINK_... constants.
labelsmatrix.MatrixThe cluster label of each row.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

FitPredict

#
func FitPredict(x &: matrix.Matrix): matrix.Matrix

Fits and returns the cluster label of each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

MiniBatchKMeans

#
struct MiniBatchKMeans

k-means on small batches, for large data.

NameTypeDescription
kint = 8The number of neighbours or clusters.
batch_sizeint = 64The batch size.
max_iterint = 200The maximum number of iterations.
seedi64 = 42The random seed, for a repeatable result.
centersmatrix.MatrixThe cluster centres.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

FitPredict

#
func FitPredict(x &: matrix.Matrix): matrix.Matrix

Fits and returns the cluster label of each row.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

DecisionTree

#
struct DecisionTree

A decision tree for classification or regression.

NameTypeDescription
criterionintThe split criterion, one of the TREE_... constants.
max_depthint = 16The maximum tree depth.
min_samples_splitint = 2The minimum number of samples needed to split a node.
min_samples_leafint = 1The minimum number of samples in a leaf.
max_featuresint = 0How many features each split tries; zero means all of them.
seedi64 = 42The random seed, for a repeatable result.
n_classes_hintint = 0The number of classes, if it is known in advance.
featureVector<int>The split feature of each node.
thresholdVector<f64>The split threshold of each node.
leftVector<int>The left child of each node.
rightVector<int>The right child of each node.
valuematrix.MatrixThe value or probabilities of the leaves.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Trees.salam

IsRegression

#
func IsRegression(): bool

Whether the model is a regression, not a classifier.

The example for this item is shown with the ones above: ai-ml-Trees.salam

NodeCount

#
func NodeCount(): int

The number of nodes.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Trees.salam

ApplyRow

#
func ApplyRow(x &: matrix.Matrix, i: int): int

The leaf the row ends up in.

The example for this item is shown with the ones above: ai-ml-Trees.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

RandomForest

#
struct RandomForest

A random forest: many trees on random samples.

NameTypeDescription
n_treesint = 100The number of trees.
criterionintThe split criterion, one of the TREE_... constants.
max_depthint = 16The maximum tree depth.
min_samples_leafint = 1The minimum number of samples in a leaf.
max_featuresint = 0How many features each split tries; zero means all of them.
bootstrapbool = trueSample with replacement.
seedi64 = 42The random seed, for a repeatable result.
workersint = 0The number of threads; zero means automatic.
treesVector<DecisionTree>The trees.
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Trees.salam

IsRegression

#
func IsRegression(): bool

Whether the model is a regression, not a classifier.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Fit

#
func Fit(x &: matrix.Matrix, y &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Trees.salam

PredictProba

#
func PredictProba(x &: matrix.Matrix): matrix.Matrix

The probability of each class for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Predict

#
func Predict(x &: matrix.Matrix): matrix.Matrix

The prediction for each row.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Score

#
func Score(x &: matrix.Matrix, y &: matrix.Matrix): f64

The score on the data: accuracy for classification and R² for regression.

The example for this item is shown with the ones above: ai-ml-Trees.salam

FreeTrees

#
func FreeTrees()

Frees the trees.

The example for this item is shown with the ones above: ai-ml-Trees.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Trees.salam

StandardScaler

#
struct StandardScaler

Gives every column a mean of zero and a standard deviation of one.

NameTypeDescription
with_meanbool = trueWhether to subtract the mean.
with_stdbool = trueWhether to divide by the standard deviation.
meanmatrix.MatrixThe column means.
stdmatrix.MatrixThe column standard deviations.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Fits the model on the training data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(x &: matrix.Matrix): matrix.Matrix

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

MinMaxScaler

#
struct MinMaxScaler

Maps every column onto the range lo to hi.

NameTypeDescription
lof64 = 0The output minimum.
hif64 = 1The output maximum.
data_minmatrix.MatrixThe column minimums.
data_rangematrix.MatrixThe column ranges.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(x &: matrix.Matrix): matrix.Matrix

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

LabelEncoder

#
struct LabelEncoder

Turns text labels into numbers.

NameTypeDescription
classesVector<str>The labels, in number order.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(labels &: Vector<str>): bool

IndexOf

#
func IndexOf(label: str): int

The number of a label, or -1 if it is not there.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Transform

#
func Transform(labels &: Vector<str>): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(labels &: Vector<str>): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(y &: matrix.Matrix): Vector<str>

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

OneHotEncoder

#
struct OneHotEncoder

Turns a class number into a one-hot vector.

NameTypeDescription
n_classesint = 0The number of classes.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(y &: matrix.Matrix): bool

Transform

#
func Transform(y &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(y &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

InverseTransform

#
func InverseTransform(onehot &: matrix.Matrix): matrix.Matrix

Undoes the transform.

The example for this item is shown with the ones above: ai-ml-Prep.salam

SimpleImputer

#
struct SimpleImputer

Fills in missing values, meaning NaN.

NameTypeDescription
strategyintThe strategy, one of the IMPUTE_... constants.
fillf64 = 0The value for the constant strategy.
statsmatrix.MatrixThe replacement value for each column.
okbool = falseWhether the fit succeeded.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Fit

#
func Fit(x &: matrix.Matrix): bool

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

FitTransform

#
func FitTransform(x &: matrix.Matrix): matrix.Matrix

Fits, then transforms the same data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: ai-ml-Prep.salam

PolynomialFeatures

#
struct PolynomialFeatures

Polynomial features and the cross products.

NameTypeDescription
degreeint = 2The degree.
include_biasbool = falseWhether to add a column of ones too.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Transform

#
func Transform(x &: matrix.Matrix): matrix.Matrix

Transforms the data.

The example for this item is shown with the ones above: ai-ml-Prep.salam

Constants and variables

KNN_BRUTE

#
const KNN_BRUTE: i32 = 0

Neighbour search: compare against every row.

The example for this item is shown with the ones above: ai-ml-Classify.salam

KNN_KDTREE

#
const KNN_KDTREE: i32 = 1

Neighbour search: a k-d tree, fast in low dimensions.

The example for this item is shown with the ones above: ai-ml-Classify.salam

TREE_GINI

#
const TREE_GINI: i32 = 0

Split criterion: Gini.

The example for this item is shown with the ones above: ai-ml-Trees.salam

TREE_ENTROPY

#
const TREE_ENTROPY: i32 = 1

Split criterion: entropy.

The example for this item is shown with the ones above: ai-ml-Trees.salam

TREE_MSE

#
const TREE_MSE: i32 = 2

Split criterion: mean squared error, for regression.

The example for this item is shown with the ones above: ai-ml-Trees.salam

IMPUTE_MEAN

#
const IMPUTE_MEAN: i32 = 0

Impute with the mean.

The example for this item is shown with the ones above: ai-ml-Prep.salam

IMPUTE_MEDIAN

#
const IMPUTE_MEDIAN: i32 = 1

Impute with the median.

The example for this item is shown with the ones above: ai-ml-Prep.salam

IMPUTE_CONSTANT

#
const IMPUTE_CONSTANT: i32 = 2

Impute with a constant value.

The example for this item is shown with the ones above: ai-ml-Prep.salam

ML_TOL

#
const ML_TOL: f64 = 1e-06

The default tolerance.

The example for this item is shown with the ones above: ai-ml-Prep.salam

KERNEL_LINEAR

#
const KERNEL_LINEAR: i32 = 0

The linear kernel.

The example for this item is shown with the ones above: ai-ml-Classify.salam

KERNEL_RBF

#
const KERNEL_RBF: i32 = 1

The Gaussian radial basis function (RBF) kernel.

The example for this item is shown with the ones above: ai-ml-Classify.salam

KERNEL_POLY

#
const KERNEL_POLY: i32 = 2

The polynomial kernel.

The example for this item is shown with the ones above: ai-ml-Classify.salam

LINK_SINGLE

#
const LINK_SINGLE: i32 = 0

Linkage: the two closest members.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

LINK_COMPLETE

#
const LINK_COMPLETE: i32 = 1

Linkage: the two farthest members.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

LINK_AVERAGE

#
const LINK_AVERAGE: i32 = 2

Linkage: the mean of the distances.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

Functions

NewKDTree

#
func NewKDTree(x &: matrix.Matrix, leaf_size: int): KDTree

A k-d tree over the data, with a leaf size.

The example for this item is shown with the ones above: ai-ml-Trees.salam

SilhouetteScore

#
func SilhouetteScore(x &: matrix.Matrix, labels &: matrix.Matrix): f64

The silhouette score; close to one means compact, well separated clusters.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

AdjustedRandIndex

#
func AdjustedRandIndex(a &: matrix.Matrix, b &: matrix.Matrix): f64

The adjusted Rand index; one means the labels are exactly the true clustering.

The example for this item is shown with the ones above: ai-ml-Cluster.salam

LabelsToInts

#
func LabelsToInts(y &: matrix.Matrix): Vector<int>

Float labels as integers.

The example for this item is shown with the ones above: ai-ml-Prep.salam

CountClasses

#
func CountClasses(y &: matrix.Matrix): int

The number of classes.

The example for this item is shown with the ones above: ai-ml-Prep.salam

NewElasticNet

#
func NewElasticNet(alpha: f64, l1_ratio: f64): Lasso

An elastic net: a mix of L1 and L2.

The example for this item is shown with the ones above: ai-ml-Linear.salam

Accuracy

#
func Accuracy(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Accuracy: the share of correct predictions.

The example for this item is shown with the ones above: ai-ml-Linear.salam

ConfusionMatrix

#
func ConfusionMatrix(y &: matrix.Matrix, pred &: matrix.Matrix, n_classes: int): matrix.Matrix

The confusion matrix; rows are the true class and columns the prediction.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Precision

#
func Precision(y &: matrix.Matrix, pred &: matrix.Matrix, positive: f64): f64

Precision: how many of the positive predictions were right.

The example for this item is shown with the ones above: ai-ml-Classify.salam

Recall

#
func Recall(y &: matrix.Matrix, pred &: matrix.Matrix, positive: f64): f64

Recall: how many of the real positives were found.

The example for this item is shown with the ones above: ai-ml-Classify.salam

F1

#
func F1(y &: matrix.Matrix, pred &: matrix.Matrix, positive: f64): f64

The harmonic mean of precision and recall.

The example for this item is shown with the ones above: ai-ml-Classify.salam

MacroF1

#
func MacroF1(y &: matrix.Matrix, pred &: matrix.Matrix, n_classes: int): f64

The mean F1 over all classes.

The example for this item is shown with the ones above: ai-ml-Classify.salam

RocAuc

#
func RocAuc(y &: matrix.Matrix, score &: matrix.Matrix): f64

The area under the ROC curve.

The example for this item is shown with the ones above: ai-ml-Classify.salam

LogLoss

#
func LogLoss(y &: matrix.Matrix, proba &: matrix.Matrix): f64

The log loss of the probabilities.

The example for this item is shown with the ones above: ai-ml-Classify.salam

MSE

#
func MSE(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Mean squared error.

The example for this item is shown with the ones above: ai-ml-Linear.salam

MAE

#
func MAE(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Mean absolute error.

The example for this item is shown with the ones above: ai-ml-Linear.salam

RMSE

#
func RMSE(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Root mean squared error.

The example for this item is shown with the ones above: ai-ml-Linear.salam

R2Score

#
func R2Score(y &: matrix.Matrix, pred &: matrix.Matrix): f64

The coefficient of determination, R².

The example for this item is shown with the ones above: ai-ml-Linear.salam

RocCurve

#
func RocCurve(y &: matrix.Matrix, score &: matrix.Matrix): matrix.Matrix

The points of the ROC curve: false positive rate, true positive rate and threshold.

The example for this item is shown with the ones above: ai-ml-Classify.salam

PrecisionRecallCurve

#
func PrecisionRecallCurve(y &: matrix.Matrix, score &: matrix.Matrix): matrix.Matrix

The points of the precision and recall curve.

The example for this item is shown with the ones above: ai-ml-Classify.salam

AveragePrecision

#
func AveragePrecision(y &: matrix.Matrix, score &: matrix.Matrix): f64

Average precision.

The example for this item is shown with the ones above: ai-ml-Classify.salam

BalancedAccuracy

#
func BalancedAccuracy(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Balanced accuracy, for imbalanced classes.

The example for this item is shown with the ones above: ai-ml-Classify.salam

MatthewsCorrCoef

#
func MatthewsCorrCoef(y &: matrix.Matrix, pred &: matrix.Matrix): f64

The Matthews correlation coefficient.

The example for this item is shown with the ones above: ai-ml-Classify.salam

CohenKappa

#
func CohenKappa(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Cohen's kappa.

The example for this item is shown with the ones above: ai-ml-Classify.salam

ExplainedVariance

#
func ExplainedVariance(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Explained variance.

The example for this item is shown with the ones above: ai-ml-Linear.salam

MedianAbsoluteError

#
func MedianAbsoluteError(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Median absolute error.

The example for this item is shown with the ones above: ai-ml-Linear.salam

MAPE

#
func MAPE(y &: matrix.Matrix, pred &: matrix.Matrix): f64

Mean absolute percentage error.

The example for this item is shown with the ones above: ai-ml-Linear.salam

TrainTestSplit

#
func TrainTestSplit(x &: matrix.Matrix, y &: matrix.Matrix, test_frac: f64, seed: i64): Split

Splits the data into training and test sets, with a seed.

The example for this item is shown with the ones above: ai-ml-Prep.salam

KFold

#
func KFold(n: int, k: int, shuffle: bool, seed: i64): Folds

k folds, with optional shuffling.

The example for this item is shown with the ones above: ai-ml-Prep.salam

StratifiedKFold

#
func StratifiedKFold(y &: matrix.Matrix, k: int, seed: i64): Folds

k folds with the same class proportions in every fold.

The example for this item is shown with the ones above: ai-ml-Prep.salam

CrossValScore

#
func CrossValScore(fitpred: func(matrix.Matrix, matrix.Matrix, matrix.Matrix): matrix.Matrix, metric: func(matrix.Matrix, matrix.Matrix): f64, x &: matrix.Matrix, y &: matrix.Matrix, folds &: Folds): Vector<f64>

The score of each fold, from a fit-and-predict function and a scoring function.

The example for this item is shown with the ones above: ai-ml-Select.salam

MeanScore

#
func MeanScore(scores &: Vector<f64>): f64

The mean of the scores.

The example for this item is shown with the ones above: ai-ml-Select.salam

CrossValScoreParallel

#
func CrossValScoreParallel(fitpred: func(matrix.Matrix, matrix.Matrix, matrix.Matrix): matrix.Matrix, metric: func(matrix.Matrix, matrix.Matrix): f64, x &: matrix.Matrix, y &: matrix.Matrix, folds &: Folds, workers: int): Vector<f64>

The same, on several threads.

The example for this item is shown with the ones above: ai-ml-Select.salam

GridSearch

#
func GridSearch(candidates &: Vector<Candidate>, metric: func(matrix.Matrix, matrix.Matrix): f64, x &: matrix.Matrix, y &: matrix.Matrix, folds &: Folds, workers: int): GridResult

Finds the best candidate by cross-validation.

The example for this item is shown with the ones above: ai-ml-Select.salam