@jsmlt/jsmlt
Version:
JavaScript Machine Learning
586 lines (496 loc) • 18.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getShape = getShape;
exports.getArrayElement = getArrayElement;
exports.setArrayElement = setArrayElement;
exports.full = full;
exports.zeros = zeros;
exports.fill = fill;
exports.concatenate = concatenate;
exports.repeat = repeat;
exports.pad = pad;
exports.internalSum = internalSum;
exports.sum = sum;
exports.power = power;
exports.abs = abs;
exports.permuteRows = permuteRows;
exports.permuteAxes = permuteAxes;
exports.flatten = flatten;
exports.transpose = transpose;
exports.reshape = reshape;
exports.subBlock = subBlock;
exports.slice = slice;
exports.equal = equal;
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 mutation 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
});
}
/**
* Randomly permute the rows of a matrix.
*
* @param {Array.<Array.<mixed>>} S Matrix
* @param {Array.<Array.<mixed>>} ... Other matrices to permute in the same way
* @return {Array.<Array.<mixed>>} Permuted matrix
*/
function permuteRows() {
for (var _len3 = arguments.length, S = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
S[_key3] = arguments[_key3];
}
// Copy matrices
var SPermutated = S.map(function (A) {
return A.slice();
});
// Number of remaining rows
var remainingRows = SPermutated[0].length;
while (remainingRows > 0) {
// Select a random element from the remaining rows and swap it with the first element that has
// not yet been assigned
var swapIndex = Math.floor(Math.random() * remainingRows);
for (var i = 0; i < SPermutated.length; i += 1) {
var tmpRow = SPermutated[i][remainingRows - 1];
SPermutated[i][remainingRows - 1] = SPermutated[i][swapIndex];
SPermutated[i][swapIndex] = tmpRow;
}
remainingRows -= 1;
}
return SPermutated;
}
/**
* Permute the axes of an input array. In other words, you can interchange the axes of an
* n-dimensional input array.
*
* @param {Array.<mixed>} A - Array of which the axes should be permuted
* @param {Array.<number>} newAxes - For the i-th element of this array, specify the index of the
* axis in the original array that should be used
* @return {Array.<mixed>} Array with permuted axes
*/
function permuteAxes(A, newAxes) {
// Shape of the input array
var oldShape = getShape(A);
// Initialize the output array as all-zeros
var newShape = newAxes.map(function (x) {
return oldShape[x];
});
var APermuted = zeros(newShape);
// Axes are permuted by, for all old array indices, copying the value at that position to the
// corresponding new position in the output array. This is a really naive algorithm, and could
// be optimized. The function below iterates over all indices in the i-th original array
// dimension, and is recursively called until the last dimension is reached
var permuteAxesStep = function permuteAxesStep(index, step) {
var _loop2 = function _loop2(i) {
var oldIndex = [].concat(_toConsumableArray(index), [i]);
if (step < oldShape.length - 1) {
permuteAxesStep(oldIndex, step + 1);
} else {
var newIndex = newAxes.map(function (axis) {
return oldIndex[axis];
});
APermuted = setArrayElement(APermuted, newIndex, getArrayElement(A, oldIndex));
}
};
for (var i = 0; i < oldShape[step]; i += 1) {
_loop2(i);
}
};
permuteAxesStep([], 0);
return APermuted;
}
/**
* Recursively flatten an array.
*
* @param {Array.<mixed>} A - Array to be flattened
* @return {Array.<mixed>} Flattened array
*/
function flatten(A) {
var _ref2;
return (_ref2 = []).concat.apply(_ref2, _toConsumableArray(A.map(function (x) {
return Array.isArray(x) ? flatten(x) : x;
})));
}
/**
* Get the transpose of a matrix or vector.
*
* @param {Array.<Array.<number>>} A - Matrix or vector
* @return {Array.<Array.<number>>} Transpose of the matrix
*/
function transpose(A) {
var ATranspose = zeros([A[0].length, A.length]);
for (var i = 0; i < A.length; i += 1) {
for (var j = 0; j < A[0].length; j += 1) {
ATranspose[j][i] = A[i][j];
}
}
return ATranspose;
}
/**
* Reshape an array into a different shape.
*
* @param {Array.<mixed>} A - Array to reshape
* @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>} Reshaped array
*/
function reshape(A, shape) {
var AValues = flatten(A);
var B = zeros(shape);
var counters = zeroVector(shape.length);
var counterIndex = counters.length - 1;
var counterTotal = 0;
var done = false;
while (!done) {
B = setArrayElement(B, counters, AValues[counterTotal]);
// Increment current counter
counterIndex = counters.length - 1;
counters[counterIndex] += 1;
counterTotal += 1;
// If the end of the current counter is reached, move to the next counter...
while (counters[counterIndex] === shape[counterIndex]) {
// ...unless we have reached the end of all counters. In that case, we are done
if (counterIndex === 0) {
done = true;
}
counters[counterIndex - 1] += 1;
counters[counterIndex] = 0;
counterIndex -= 1;
}
}
return B;
}
/**
* Extract a sub-block of a matrix of a particular shape at a particular position.
*
* @deprecated Use slice() instead
*
* @param {Array.<mixed>} A - Array to extract block from
* @param {Array.<number>} offset - Array specifying the offset per dimension. n-th element
* corresponds to the number of elements to skip, before extracting the block, in the n-th
* dimension.
* @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>} Sub-block extracted from array
*/
function subBlock(A, offset, shape) {
if (offset.length === 1) {
return A.slice(offset[0], offset[0] + shape[0]);
}
var subblock = [];
for (var i = offset[0]; i < offset[0] + shape[0]; i += 1) {
subblock.push(subBlock(A[i], offset.slice(1), shape.slice(1)));
}
return subblock;
}
/**
* Take a slice out of an input array. Negative indices can be used in both the starting indices and
* the stopping indices. Negative indices: the negative stopping index is used as the negative
* offset relative to the last index in the particular dimension.
*
* @param {Array.<mixed>} A - Array to extract block from
* @param {Array.<number>} start - Array specifying the starting index per dimension. n-th element
* corresponds to the number of elements to skip, before extracting the block, in the n-th
* dimension. Negative indices are supported.
* @param {Array.<number>} stop - Array specifying the index to stop at (exclusive) per dimension.
* n-th element corresponds to the stopping index in the n-th dimension. Negative indices are
* supported. Use null for unlimited offset.
* @return {Array.<mixed>} Array slice extracted from input array
*/
function slice(A, start, stop) {
// Check whether the same number of start and stop indices is supplied
if (start.length !== stop.length) {
throw new Error('"start" and "stop" must contain the same number of indices.');
}
// Check whether the number of dimensions to slice on does not exceed the number of dimensions of
// the array
if (start.length > getShape(A).length) {
throw new Error('The number of start and stop indices must not exceed the number of input array dimensions');
}
// Parse start and end indices for highest dimension
var parseIndex = function parseIndex(index, allowNull) {
if (allowNull && index === null) {
return A.length;
}
if (index < 0) {
return A.length + index;
}
return index;
};
var parsedStart = parseIndex(start[0], false);
var parsedStop = parseIndex(stop[0], true);
// If this is the deepest dimension where we should slice, simply slice the array
if (start.length === 1) {
return A.slice(parsedStart, parsedStop);
}
// If it isn't the deepest dimension to slice, slice in the sub-array
var subslice = [];
for (var i = parsedStart; i < parsedStop; i += 1) {
subslice.push(slice(A[i], start.slice(1), stop.slice(1)));
}
return subslice;
}
/**
* Deep check whether two arrays are equal: sub-arrays will be traversed, and strong type checking
* is enabled.
*
* @param {Array.<mixed>|mixed} array1 - First array to check or array element to check
* @param {Array.<mixed>|mixed} array2 - Second array to check ot array element to check. Will be
* checked against first array
* @return {boolean} Whether the two arrays are the same
*/
function equal(array1, array2) {
if (!Array.isArray(array1) || !Array.isArray(array2)) {
return array1 === array2;
}
if (array1.length !== array2.length) {
return false;
}
return array1.reduce(function (r, a, i) {
return r && equal(a, array2[i]);
}, true);
}