UNPKG

@jsmlt/jsmlt

Version:

JavaScript Machine Learning

396 lines (345 loc) 11.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getShape = getShape; exports.getArrayElement = getArrayElement; exports.setArrayElement = setArrayElement; exports.linspace = linspace; exports.valueVector = valueVector; exports.zeroVector = zeroVector; exports.full = full; exports.zeros = zeros; exports.fill = fill; exports.concatenate = concatenate; exports.repeat = repeat; exports.pad = pad; exports.dot = dot; exports.norm = norm; exports.sum = sum; exports.power = power; exports.scale = scale; exports.internalSum = internalSum; exports.abs = abs; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /** * Multidimensional array toolkit for JavaScript. Similar to numpy in functionality. Mainly works * using plain JavaScript arrays. */ /** * Find the shape of an array, i.e. the number of elements per dimension of the array. * * @param {Array.<mixed>} A - Arbitrarily nested array to find shape of. * @return {Array.<number>} Array specifying the number of elements per dimension. n-th * element corresponds to the number of elements in the n-th dimension. */ function getShape(A) { if (!Array.isArray(A)) { return []; } var B = getShape(A[0]); B.unshift(A.length); return B; } /** * Get an arbitrary element from an array, using another array to determine the index inside the * first array. * * @param {Array.<mixed>} A - Array to get an element from * @param {Array.<number>} index - Indices to find array element. n-th element corresponds to index * in n-th dimension * @return {mixed} Array element value at index */ function getArrayElement(A, index) { if (index.length === 1) { return A[index]; } return getArrayElement(A[index[0]], index.slice(1)); } /** * Set an arbitrary element in an array, using another array to determine the index inside the * array. * * @param {Array.<mixed>} A - Array to set an element in * @param {Array.<number>} index - Indices to find array element. n-th element corresponds to index * in n-th dimension * @param {mixed} value New element value at index */ function setArrayElement(A, index, value) { var B = A.slice(); B[index[0]] = index.length === 1 ? value : setArrayElement(A[index[0]], index.slice(1), value); return B; } /** * Generate n points on the interval (a,b), with intervals (b-a)/(n-1). * * @example * var list = linspace(1, 3, 0.5); * // list now contains [1, 1.5, 2, 2.5, 3] * * @param {number} a - Starting point * @param {number} b - Ending point * @param {number} n - Number of points * @return {Array.<number>} Array of evenly spaced points on the interval (a,b) */ function linspace(a, b, n) { var r = []; for (var i = 0; i < n; i += 1) { r.push(a + i * ((b - a) / (n - 1))); } return r; } /** * Initialize a vector of a certain length with a specific value in each entry. * * @param {number} n - Number of elements in the vector * @param {mixed} value - Value to initialize entries at * @return Array Vector of n elements of the specified value */ function valueVector(n, value) { return [].concat(_toConsumableArray(Array(n))).map(function () { return value; }); } /** * Initialize a zero vector of a certain length. * * @param {number} n - Number of elements in the vector * @return {Array} Vector of n elements of value 0 */ function zeroVector(n) { return valueVector(n, 0); } /** * Initialize an n-dimensional array of a certain value. * * @param {Array.<number>} shape - Array specifying the number of elements per dimension. n-th * element corresponds to the number of elements in the n-th dimension. * @param {mixed} value - Value to fill the array with * @return {Array.<mixed>} Array of the specified with zero in all entries */ function full(shape, value) { if (!Array.isArray(shape)) { return valueVector(shape, value); } if (shape.length === 1) { return valueVector(shape[0], value); } return [].concat(_toConsumableArray(Array(shape[0]))).map(function () { return full(shape.slice(1), value); }); } /** * Initialize an n-dimensional array of zeros. * * @param {Array.<number>} shape - Array specifying the number of elements per dimension. n-th * element corresponds to the number of elements in the n-th dimension. * @return {Array.<mixed>} Array of the specified with zero in all entries */ function zeros(shape) { return full(shape, 0); } /** * Set all entries in an array to a specific value and return the resulting array. Original array * is not modified. * * @param {Array.<mixed>} A - Array of which entries should be changed * @param {mixed} value - Value the array entries should be changed to * @return {Array.<mixed>} Array with modified entries */ function fill(A, value) { return A.map(function (B) { return Array.isArray(B) ? fill(B, value) : value; }); } /** * Concatenate two or more n-dimensional arrays. * * @param {number} axis - Axis to perform concatenation on * @param {...Array.<mixed>} S - Arrays to concatenate. They must have the same shape, except in * the dimension corresponding to axis (the first, by default) * @return {Array} Concatenated array */ function concatenate(axis) { for (var _len = arguments.length, S = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { S[_key - 1] = arguments[_key]; } if (axis === 0) { var _ref; return (_ref = []).concat.apply(_ref, S); } var A = []; var _loop = function _loop(i) { A.push(concatenate.apply(undefined, [axis - 1].concat(_toConsumableArray(S.map(function (APrime) { return APrime[i]; }))))); }; for (var i = 0; i < S[0].length; i += 1) { _loop(i); } return A; } /** * Repeat an array multiple times along an axis. This is essentially one or more concatenations of * an array with itself. * * @param {number} axis - Axis to perform repetition on * @param {number} numRepeats - Number of times to repeat the array * @param {Array.<mixed>} A - Array to repeat * @return {Array.<mixed>} Specified array repeated numRepeats times */ function repeat(axis, numRepeats, A) { var R = A.slice(); for (var i = 0; i < numRepeats - 1; i += 1) { R = concatenate(axis, R, A); } return R; } /** * Pad an array along one or multiple axes. * * @param {Array.<mixed>} A - Array to be padded * @param {Array.<number> | Array.<Array.<number>>} paddingLengths - Amount of padding for each axis * that should be padded. Each element in this array should be a two-dimensional array, where the * first element specifies the padding at the start (front) of the axis, and the second element * specifies the padding at the end (back) of the axis. The nth element of `paddingLength` * specifies the front and back padding of the nth axis in the `axes` parameter * @param {Array.<number> | Array.<Array.<number>>} paddingValues - The values to pad each axis * with. See the specification of the `paddingLenghts` parameter for the expected structure * @param {Array.<number>} [axes] - Indices of axes to be padded. Defaults to the first n axes, * where n is the number of elements in `paddingLengths` * @return {Array.<mixed>} Padded array */ function pad(A, paddingLengths, paddingValues) { var axes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; var B = A.slice(); // Use default axes to padded (first n axes where n is the number of axes used in paddingLenghts // and paddingValues) if (!axes.length) { for (var i = 0; i < paddingLengths.length; i += 1) { axes.push(i); } } // Pad all specified axes for (var _i = 0; _i < axes.length; _i += 1) { var axis = axes[_i]; var currentShape = getShape(B); // Determine padding lengths var lengthFront = 0; var lengthBack = 0; if (Array.isArray(paddingLengths[_i])) { lengthFront = paddingLengths[_i][0]; lengthBack = paddingLengths[_i][1]; } else { lengthFront = paddingLengths[_i]; lengthBack = paddingLengths[_i]; } // Determine padding values var valueFront = 0; var valueBack = 0; if (Array.isArray(paddingValues[_i])) { valueFront = paddingValues[_i][0]; valueBack = paddingValues[_i][1]; } else { valueFront = paddingValues[_i]; valueBack = paddingValues[_i]; } // Shape of padding for front and back var shapeFront = currentShape.slice(); var shapeBack = currentShape.slice(); shapeFront[axis] = lengthFront; shapeBack[axis] = lengthBack; // Create padding blocks var paddingFront = full(shapeFront, valueFront); var paddingBack = full(shapeBack, valueBack); B = concatenate(axis, paddingFront, B, paddingBack); } return B; } /** * Calculate dot product of two vectors. Vectors should have same size. * * @param {Array.<number>} x - First vector * @param {Array.<number>} y - Second vector * @return {number} Dot product scalar result */ function dot(x, y) { return x.reduce(function (r, a, i) { return r + a * y[i]; }, 0); } /** * Calculate the Euclidian norm of a vector. * * @param {Array.<number>} x - Vector of which to calculate the norm */ function norm(x) { return Math.sqrt(dot(x, x)); } /** * Calculate elementwise sum of two or more arrays. Arrays should have the same shape. * * @param {...Array.<mixed>} S - Arrays to concatenate. They must have the same shape * @return {Array.<mixed>} Sum of arrays */ function sum() { for (var _len2 = arguments.length, S = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { S[_key2] = arguments[_key2]; } return S.reduce(function (r, a) { return r.map(function (b, i) { return Array.isArray(b) ? sum(b, a[i]) : b + a[i]; }); }); } /** * Raise all elements in an array to some power. The power to raise the elements to can either be * the same number for all elements, in which case it should be passed as a number, or an individual * number for all elements, in which case it should be passed as an array of the same shape as the * input array. * * @param {Array.<number>} x - Input array * @param {number|Array.<number>} y - The power to raise all elements to. Either a {number} (all * elements will be raised to this power) or an array (elements in the input array will be raised * to the power specified at the same position in the powers array) * @return {Array.<number>} Array containing the input elements, raised to the specified power */ function power(x, y) { return Array.isArray(x) ? x.map(function (a, i) { return power(a, Array.isArray(y) ? y[i] : y); }) : Math.pow(x, y); } /** * Multiply a vector by a scalar (i.e. scale the vector). * * @param {Array.<number>} x - Vector * @param {number} c - Scalar * @return {Array.<number>} Scaled vector */ function scale(x, c) { return x.map(function (a) { return c * a; }); } /** * Sum all elements of an array. * * @param {Array.<number>} A - Array * @return {number} Sum of all vector elements */ function internalSum(A) { return A.reduce(function (r, B) { return r + (Array.isArray(B) ? internalSum(B) : B); }, 0); } /** * Get a copy of an array with absolute values of the original array entries. * * @param {Array.<mixed>} A Array to get absolute values array from * @return {Array.<mixed>} Array with absolute values */ function abs(A) { return A.map(function (B) { return Array.isArray(B) ? abs(B) : Math.abs(B); }); }