Classic machine learning: preprocessing, regression, classification, trees, clustering and evaluation.
Types
A k-d tree for nearest neighbour search.
Name Type Description 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 Copy
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
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
Linear regression by least squares.
Name Type Description fit_interceptbool = trueWhether to fit an intercept too. coefmatrix.MatrixThe coefficients. interceptf64 = 0The intercept. okbool = falseWhether the fit succeeded.
ai-ml-Linear.salam Copy
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Linear.salam
Ridge regression: linear with an L2 penalty.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Linear.salam
Lasso: linear with an L1 penalty that drives unimportant coefficients to zero; with an l1_ratio below one it is an elastic net.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Linear.salam
struct LogisticRegression Logistic regression for classification, with any number of classes.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Linear.salam
One histogram boosting tree.
Name Type Description 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 Copy
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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
struct HistGradientBoosting Histogram gradient boosting, fast on large data, like LightGBM.
Name Type Description 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
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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
The example for this item is shown with the ones above: ai-ml-Trees.salam
Linear discriminant analysis.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
Quadratic discriminant analysis, with a separate covariance for each class.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Classify.salam
Name Type Description 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 Copy
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
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
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
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
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Cluster.salam
The example for this item is shown with the ones above: ai-ml-Cluster.salam
Density clustering; it finds the number of clusters itself and sets the noise apart.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
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
The example for this item is shown with the ones above: ai-ml-Cluster.salam
A linear support vector machine.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
A kernel support vector machine.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
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
The number of support vectors.
The example for this item is shown with the ones above: ai-ml-Classify.salam
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Classify.salam
AdaBoost with shallow trees.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
The example for this item is shown with the ones above: ai-ml-Trees.salam
Gradient boosting with trees.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
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
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Trees.salam
The example for this item is shown with the ones above: ai-ml-Trees.salam
Name Type Description x_trainmatrix.MatrixThe training features. x_testmatrix.MatrixThe test features. y_trainmatrix.MatrixThe training labels. y_testmatrix.MatrixThe test labels.
ai-ml-Prep.salam Copy
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
The example for this item is shown with the ones above: ai-ml-Prep.salam
Name Type Description 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
The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
The result of a grid search.
Name Type Description scoresVector<f64>The mean score of each candidate. bestint = -1The number of the best one. best_scoref64 = 0The best score.
ai-ml-Select.salam Copy
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
The example for this item is shown with the ones above: ai-ml-Select.salam
One candidate in a grid search.
Name Type Description 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
Principal component analysis, for reducing dimensions.
Name Type Description 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
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
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (z &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
Truncated singular value decomposition: like PCA without subtracting the mean, for sparse data.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (z &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
Gaussian naive Bayes, for continuous features.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
Multinomial naive Bayes, for counts such as in text classification.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
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
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Classify.salam
t-SNE, for showing high-dimensional data in two or three dimensions.
Name Type Description 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
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
The example for this item is shown with the ones above: ai-ml-Cluster.salam
A k nearest neighbours classifier.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Classify.salam
A k nearest neighbours regressor.
Name Type Description 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
func Fit (x &: matrix.Matrix, y &: matrix.Matrix): bool
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
func Score (x &: matrix.Matrix, y &: matrix.Matrix): f64
The example for this item is shown with the ones above: ai-ml-Classify.salam
A Gaussian mixture model, fitted with EM.
Name Type Description 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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Cluster.salam
Agglomerative hierarchical clustering.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
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
The example for this item is shown with the ones above: ai-ml-Cluster.salam
k-means on small batches, for large data.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
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
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
The example for this item is shown with the ones above: ai-ml-Cluster.salam
A decision tree for classification or regression.
Name Type Description 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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
A random forest: many trees on random samples.
Name Type Description 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
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
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
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
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
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
The example for this item is shown with the ones above: ai-ml-Trees.salam
The example for this item is shown with the ones above: ai-ml-Trees.salam
Gives every column a mean of zero and a standard deviation of one.
Name Type Description 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
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
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
Maps every column onto the range lo to hi.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
Turns text labels into numbers.
Name Type Description 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
func Fit (labels &: Vector < str >): bool
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
func Transform (labels &: Vector < str >): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (y &: matrix.Matrix): Vector < str > The example for this item is shown with the ones above: ai-ml-Prep.salam
The example for this item is shown with the ones above: ai-ml-Prep.salam
Turns a class number into a one-hot vector.
Name Type Description 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
func Fit (y &: matrix.Matrix): bool
func Transform (y &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
func InverseTransform (onehot &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
Fills in missing values, meaning NaN.
Name Type Description 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
func Fit (x &: matrix.Matrix): bool
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
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
The example for this item is shown with the ones above: ai-ml-Prep.salam
struct PolynomialFeatures Polynomial features and the cross products.
Name Type Description 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
func Transform (x &: matrix.Matrix): matrix.Matrix The example for this item is shown with the ones above: ai-ml-Prep.salam
Functions
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
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
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
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
func CountClasses (y &: matrix.Matrix): int The example for this item is shown with the ones above: ai-ml-Prep.salam
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
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
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
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
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
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
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
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
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
func MSE (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Linear.salam
func MAE (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Linear.salam
func RMSE (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Linear.salam
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
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
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
func AveragePrecision (y &: matrix.Matrix, score &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Classify.salam
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
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
func CohenKappa (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Classify.salam
func ExplainedVariance (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Linear.salam
func MedianAbsoluteError (y &: matrix.Matrix, pred &: matrix.Matrix): f64 The example for this item is shown with the ones above: ai-ml-Linear.salam
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
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
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
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
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
func MeanScore (scores &: Vector < f64 >): f64 The example for this item is shown with the ones above: ai-ml-Select.salam
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
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