Skip to content

lib-ml 库参考 ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793881835/FIN+5.3.1+lib-ml 中文整理基于 FIN 5.3.1

导读: 机器学习(ML)函数库

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • lib
  • meta
  • docs
  • funcs
  • Overview
    • System Requirements
  • Supervised Learning
    • Kernel Functions
  • Training and Predicting
    • Saving a Trained Model
  • Feature Scaling
  • mlAddMeta(model, meta: null)
  • mlGridSearchCv(estimator, paramGrid, opts: {})
  • mlLinearKernel()
  • mlLoadModel(handle)
  • mlMeta(model)
  • mlOls(qr: false)
  • mlParamSweep(func, paramGrid)
  • mlPolyKernel(degree, gamma: null, offset: null)
  • mlPredict(model, x)
  • mlRbfKernel(gamma: null)
  • mlSaveModel(model, handle)
  • mlScaleMinMax(features, min: 0, max: Number.one)
  • mlScaleZ(features)
  • mlStats(model)
  • mlSvm(kernel, k, opts: {})
  • mlSvr(kernel, opts: {})
  • mlToGrid(val, opts: {})
  • mlToMatrix(val)
  • mlTrain(model, x, y)

概述(中译) ​

机器学习(ML)函数库


API 正文(英文) ​

docs ​

Overview • Supervised Learning • Training and Predicting • Feature Scaling


funcs ​

mlAddMetaAdd metadata to the given trained model
mlGridSearchCvConfigure a cross-validation grid-search
mlLinearKernelCreate a Linear kernel
mlLoadModelLoad a trained model from the given I/O handle
mlMetaGet the model metadata
mlOlsCreate a training model for doing ordinary least-squares regression (OLS)
mlParamSweepDo a "parameter sweep" by invoking the given func for all combinations of parameters in the parameter grid
mlPolyKernelCreate a Polynomial kernel
mlPredictMake predictions against a trained model
mlRbfKernelCreate a RBF (RBF) kernel
mlSaveModelSave a trained model to the given I/O handle
mlScaleMinMaxPerform Min-Max feature scaling
mlScaleZPerform Z-score normalization on the features
mlStatsGet the model statistics
mlSvmCreate a Support Vector Machine (SVM) for classification
mlSvrCreate a Support Vector Machine for Regression (SVR)
mlToGridConvert a matrix to a Grid
mlToMatrixConvert the given obj to an optimized matrix type for machine learning
mlTrainTrain a machine learning model with the given training data

lib ml ​

Overview ​

The mlExt provides a library of functions to perform machine learning (ML) within SkySpark. There are three broad categories of machine learning algorithms. Currently, the ext provides support for the first category (supervised learning)

  1. Supervised Learning:

    The algorithm builds a model from input data for which the desired output values are known.

  2. Unsupervised Learning:

    The algorithm builds a model from input data for which the desired output values are not known. That is, the algorithm attempts to find the structure in the data.

  3. Reinforcement Learning:

    The algorithm interacts with a dynamic environment and learns from the consequences of its actions. It is not "trained" with data.

The general set of steps for running a machine learning algorithm are:

  1. Prepare your input data/features.
  2. Configure a particular algorithm.
  3. Train your model.
  4. Make predictions against the model.

The rest of this guide provides an overview of the capabilities of the ext and what functions are available for performing these steps.

System Requirements ​

This ext requires Java 1.8. If you get an exception similar to the following, then you are not running Java 1.8

sys::Err: java.lang.UnsupportedClassVersionError: .... details ....

Supervised Learning ​

The following algorithms are available for performing supervised learning. See the function documentation for details on configuring the various algorithms for use.

  1. Regression
    • Ordinary Least Squares (OLS). See mlOls()
    • Support Vector Regression (SVR). See mlSvr()
  2. Classification
    • Support Vector Machine (SVM), with support for binary and multiclass classification. See mlSvm()

Kernel Functions ​

Support vector machines (including SVR) require a kernel function to be configured. The following kernel functions are supported:

  • Linear Kernel. See mlLinearKernel()
  • RBF Kernel (Gaussian). See mlRbfKernel()
  • Polynomial Kernel. See mlPolyKernel()

Example:

svr: mlSvr(mlRbfKernel())

Training and Predicting ​

Once you have configured an algorithm, you can use it to train your model. See the mlTrain() function for details. The result of running that function is called a trained model. You can use a trained model to make predictions using the mlPredict() function.

svr:   mlSvr(mlLinearKernel())
model: mlTrain(svr, trainingX, trainingY)
p:     mlPredict(model, testX)

Saving a Trained Model ​

Training a model can be an expensive operation. You can save your trained model to disk using mlSaveModel(). You can load the model again using mlLoadModel().

Sometimes you need to associate some state or metadata with your trained model so that you can properly configure your test data for making predictions. Use the mlAddMeta() function to add metadata to a trained model. Any metadata associated with the model will also be saved/loaded using the the above functions You can retreive the metadata from your trained model using mlMeta().

// train a model using OLS and add some metadata
model: mlTrain(mlOls(), trainingX, trainingY)
model = model.mlAddMeta(["dates":dates, "site":site])

// save the model
model.mlSaveModel(`io/models/ols.model`)

// reload the model and get the site from the metadata
model = mlLoadModel(`io/models/ols.model`)
site  = model.mlMeta->site

Feature Scaling ​

When preparing your data for training a model, it is often necessary to perform feature scaling on the inputs/features. This process is sometimes called data normalization. Feature scaling is a method to standardize the range of values for a particular feature. Normalzing your features is often a critical step in preparing your data for modeling. For example, certain algorithms will perform very poorly if features are not scaled (e.g. SVM). Also, feature scaling will prevent a feature with a large range of values from dominating the model.

The ext has the following scaling algorithms available:

  • Min-Max Scaling: Scales the range of features to a given range. Common ranges are [0, 1] or [-1, 1]. See mlScaleMinMax()
  • Z-score Normalization: Scales the features so that they have the property that μ = 0 and σ = 1. See mlScaleZ()

Example:

trainingX = trainingX.mlScaleMinMax(0, 1)


def ​

func:mlAddMeta ​

mlAddMeta(model, meta: null) ​

Add metadata to the given trained model. See mlAddMeta() Return the trained model with updated metadata.


meta ​

deffunc:mlAddMeta
isfunc
liblib:ml
namemlAddMeta

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlGridSearchCv ​

mlGridSearchCv(estimator, paramGrid, opts: {}) ​

Configure a cross-validation grid-search. A grid search performs an exhaustive search over all specified parameter values for a given algorithm/estimator function. The parameters of the estimator are optimized by a cross-validated grid-search using the supplied parameter grid.

The configured grid-search can then be trained using mlTrain(). The result will be a "trained model" where the parameter set that produced the best "score" will be used to make predictions using mlPredict().

  • estimator: (Str or Func) The estimator to use. Can either pass the name of a function in this ext, or the func itself (e.g. "mlSvr").
  • paramGrid: (Dict or Dict[]) The parameters to explore. The keys of each Dict are the parameter names for the estimator func. The value of each key is a list of values to explore for that parameter. Every combination of parameters will be tried when training the grid search. You may omit optional parameters for the estimator. If the last parameter of the estimator is a Dict, you may include the keys of that Dict parameter in the paramGrid (see example below).
  • opts: Options to configure the behavior of the grid search. The following options are supported:
    • fold: (Number) The number of folds to apply during cross-validation. (default: 3).
    • scorer: (Str) The validation measure to use when determining the best model. The following are always computed, and you may pick one to use to determine the best fit (NOTE: currently the grid search will pick the parameter set with the highest score. So it is only makes sense to pick a measure where a high score means "good")
      • "r2": The r-squared value
      • "explainedVariance": Explained variance regression score
      • "mae": Mean Absolute Error
      • "rmse": Root Mean Squared Error

The result of running cross-validation on a parameter set is called a "run". The results of each run can be retrieved by using mlStats() on the trained model. The stats Dict will contain a key runs which is a list of of run results, sorted from best to worst based on the configured scorer.

Each run result is itself a Dict with the following keys:

  • "scores": A Dict containing all validation scores computed for that run.
  • "params": A Dict containing the parameter used to configure the estimator for that run.

Examples: ​

// Build parameter grid to explore
rbfKernels: mlParamSweep(mlRbfKernel, {"gamma":[null, 0.2]})
paramGrid: [
  {"kernel":rbfKernels},
  {"kernel":mlLinearKernel(), "c":[1,10,100]},
]

// Configure cross-validated grid-search
search: mlGridSearchCv(mlSvr, paramGrid, {"folds":10, "scorer":"r2"})

// The search is configured to train data on each of the following
// mlSvr configurations:
// 1) mlSvr(mlRbfKernel())
// 2) mlSvr(mlRbfKernel(0.2))
// 3) mlSvr(mlLinearKernel(), {"c":1})
// 4) mlSvr(mlLinearKernel(), {"c":10})
// 5) mlSvr(mlLinearKernel(), {"c":100})

// Train the grid search
model: mlTrain(search, x, y)

// Predict against the best model
predictions: mlPredict(model, predX)

// Dump the run stats for the grid search
stats: mlStats(model)
echo(stats["runs"])

meta ​

deffunc:mlGridSearchCv
isfunc
liblib:ml
namemlGridSearchCv

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlLinearKernel ​

mlLinearKernel() ​

Create a Linear kernel


meta ​

deffunc:mlLinearKernel
isfunc
liblib:ml
namemlLinearKernel

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlLoadModel ​

mlLoadModel(handle) ​

Load a trained model from the given I/O handle


meta ​

deffunc:mlLoadModel
isfunc
liblib:ml
namemlLoadModel

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlMeta ​

mlMeta(model) ​

Get the model metadata. See mlAddMeta().


meta ​

deffunc:mlMeta
isfunc
liblib:ml
namemlMeta

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlOls ​

mlOls(qr: false) ​

Create a training model for doing ordinary least-squares regression (OLS).

By default, Singular Value Decomposition (SVD) is used to fit the model. Set the qr parameter to true to use QR decomposition. QR is faster than SVD, however, it cannot handle rank-deficient matrices. If you are using QR and are getting errors, try switching back to SVD.

When training this model there is NO NEED to include a constant column of 1s for bias.

The following stats are available via mlStats() once the model has been trained.

  • coeffs: (Number[]) linear coefficients (without intercept)
  • intercept
  • residuals
  • rss: residual sum of squares
  • error: residual standard error
  • df: degree-of-freedom of residual standard error
  • r2: R-Squared statistic
  • r2adj: Adjusted R-Squared statistic
  • ftest: F-statistic of "goodness-of-fit"
  • pvalue: p-value of "goodnes-of-fit"
  • ttest: (Grid) The t-test of the coefficients (including intercept). The first column is the coefficients, the second column is the standard error of coefficients, the third column is the t-score of the hypothesis test if the coefficient is zero, the fourth column is the p-values of test. The last row is of intercept.

meta ​

deffunc:mlOls
isfunc
liblib:ml
namemlOls

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlParamSweep ​

mlParamSweep(func, paramGrid) ​

Do a "parameter sweep" by invoking the given func for all combinations of parameters in the parameter grid.

  • func: The function to invoke. You may also pass the Str name of any function in this extension.
  • paramGrid (Dict or Dict[]): They keys of each Dict are the parameter names of the func. The value of each key may be a single value, or a list of values. Every combination of the value will be used to invoke the given func

Returns a list containing the result of invoking the function for each parameter combination.

Examples:

// Get 5 instances of a configured RBF kernel
mlParamSweep(mlRbfKernel, [{"gamma": [null, 0.1, 0.2, 0.5, 1.0]}])

meta ​

deffunc:mlParamSweep
isfunc
liblib:ml
namemlParamSweep

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlPolyKernel ​

mlPolyKernel(degree, gamma: null, offset: null) ​

Create a Polynomial kernel. k(u, v) = (γ uTv - λ)^d

  • degree (d): the degree of the polynomial
  • gamma (γ): the scale of the used inner product. If null, then (1 / num_features) will be used.
  • offset (λ): the offset of the used inner product (default 0.0)

meta ​

deffunc:mlPolyKernel
isfunc
liblib:ml
namemlPolyKernel

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlPredict ​

mlPredict(model, x) ​

Make predictions against a trained model.

  • model: The trained model to make predictions against.
  • x: The test data. This value can be specified exactly as inmlTrain

If x contains a single row, the result is a Number (the output prediction).

If x contains N rows, then the result is a Number[] where the ith element corresponds to the prediction for the ith row.


meta ​

deffunc:mlPredict
isfunc
liblib:ml
namemlPredict

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlRbfKernel ​

mlRbfKernel(gamma: null) ​

Create a RBF (RBF) kernel.

  • gamma: The scale parameter of the kernel (γ > 0). If null, then (1 / num_features) will be used.

meta ​

deffunc:mlRbfKernel
isfunc
liblib:ml
namemlRbfKernel

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlSaveModel ​

mlSaveModel(model, handle) ​

Save a trained model to the given I/O handle


meta ​

deffunc:mlSaveModel
isfunc
liblib:ml
namemlSaveModel

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlScaleMinMax ​

mlScaleMinMax(features, min: 0, max: Number.one) ​

Perform Min-Max feature scaling. Each feature will be scaled to the fixed range between min and max.

  • features: The features to scale. Can be any type acceptable to mlToMatrix()
  • min: the lower bound of the range for scaling
  • max: the upper bound of the range for scaling Returns a matrix.

If a particular feature has the same min and max value, the we scale it as (max(feature) - min(feature) / 2


meta ​

deffunc:mlScaleMinMax
isfunc
liblib:ml
namemlScaleMinMax

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlScaleZ ​

mlScaleZ(features) ​

Perform Z-score normalization on the features. Feature are rescaled such that they have the properties that μ = 0 and σ = 1

  • features: The features to scale. Can be any type acceptable to mlToMatrix() Returns a matrix.

meta ​

deffunc:mlScaleZ
isfunc
liblib:ml
namemlScaleZ

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlStats ​

mlStats(model) ​

Get the model statistics. The algorithm used to train the model defines the statistics that are available.


meta ​

deffunc:mlStats
isfunc
liblib:ml
namemlStats

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlSvm ​

mlSvm(kernel, k, opts: {}) ​

Create a Support Vector Machine (SVM) for classification. The SVM can be configured for either binary or multiclass classification.

  • kernel: The kernel function

  • k: The number of classes

  • opts: A Dict containing the configuration options for the SVM. The following options are supported for both binary and multiclass SVMs:

    • c: (Number) The soft-margin penalty parameter (default 1.0).
    • tol: (Number) The tolerance of convergence/termination criteria (default 0.001)

    The following options can be used to configure a Binary SVM:

    • cn: (Number) The soft-margin penalty parameter for negative instances (default: cp)

    The following options can be used to configure a Multiclass SVM:

    • strategy: (Str) the classification strategy to use. Supported values are one_vs_one and one_vs_all. (default: one_vs_one)

Note: for a binary SVM (k=2) when you create the training data you must map all results to either -1 or 1.


meta ​

deffunc:mlSvm
isfunc
liblib:ml
namemlSvm

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlSvr ​

mlSvr(kernel, opts: {}) ​

Create a Support Vector Machine for Regression (SVR).

  • kernel: The kernel function
  • opts: A Dict containing the configuration options for the SVM. The following options are supported for both binary and multiclass SVMs:
    • c: (Number) The soft-margin penalty parameter (default 1.0).
    • eps: (Number) the loss function error threshold (default 0.1)
    • tol: (Number) The tolerance of convergence/termination criteria (default 0.001)

meta ​

deffunc:mlSvr
isfunc
liblib:ml
namemlSvr

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlToGrid ​

mlToGrid(val, opts: {}) ​

Convert a matrix to a Grid.


meta ​

deffunc:mlToGrid
isfunc
liblib:ml
namemlToGrid

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlToMatrix ​

mlToMatrix(val) ​

Convert the given obj to an optimized matrix type for machine learning. A critical difference between this matrix and the one provided by the math is that this matrix is NOT a Grid. To convert a matrix back to a grid use mlToGrid()


meta ​

deffunc:mlToMatrix
isfunc
liblib:ml
namemlToMatrix

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function


def ​

func:mlTrain ​

mlTrain(model, x, y) ​

Train a machine learning model with the given training data. A "trained model" is returned. The trained model can be used to make predictions.

  • model: A configured machine learning algorithm (e.g. SVM).
  • x: The matrix of training data. Each row of the matrix corresponds to a feature set to train. The number of columns correspond to the number of features being used in the model. May be any type that is valid for mlToMatrix().
  • y: The observation for each training set. May be a Number[] or a single-column grid. y[i] corresponds to the observation (i.e. output) of training set x[i]. The number of rows in x must match the number of elements in y.

meta ​

deffunc:mlTrain
isfunc
liblib:ml
namemlTrain

supertypes ​

featureFeature namespace of definitions formatted as feature:name
funcAxon function