UNPKG

neuralnetwork

Version:

Rudimentary Neural Network in Typescript

68 lines (66 loc) 2.16 kB
"use strict"; function dotProduct(v0, v1) { var sum = v0.reduce(function (sum, currentValue, index, array) { return sum + currentValue * v1[index]; }, 0); return sum; } exports.dotProduct = dotProduct; function vectorSum(v0, v1) { var ret = [], longer = Math.max(v0.length, v1.length), longerVector = null, other = null, temp = 0; longerVector = (longer === v0.length) ? v0 : v1; other = (longerVector === v0) ? v1 : v0; longerVector.forEach(function (el, index) { // the other index might be empty since the other vector is shorter temp = other[index] || 0; ret[index] = el + temp; }); return ret; } exports.vectorSum = vectorSum; function matrixVectorMultiplication(matrix, vec) { if (matrix.length % vec.length !== 0) { throw new Error('Matrix length should be multiple of vector length. Given: ' + matrix.length.toString() + ',' + vec.length.toString()); } if (matrix.length < vec.length) { throw new Error('Matrix too short'); } var ret = []; for (var i = 0; i < matrix.length / vec.length; i += 1) { ret.push(dotProduct(matrix.slice(i * vec.length, (i + 1) * vec.length), vec)); } return ret; } exports.matrixVectorMultiplication = matrixVectorMultiplication; function transpose(matrix, numberColumns) { var numberRows = matrix.length / numberColumns; var ret = []; for (var i = 0; i < numberRows; i += 1) { for (var j = 0; j < numberColumns; j += 1) { ret[j * numberRows + i] = matrix[i * numberColumns + j]; } } return ret; } exports.transpose = transpose; /** Zero's out a vector. But should this be pure? */ function zero(vec) { vec.forEach(function (el, index) { vec[index] = 0; }); return vec; } exports.zero = zero; function outerProduct(vec0, vec1) { var ret = []; vec0.forEach(function (v0, outerIndex) { vec1.forEach(function (v1, innerIndex) { ret[outerIndex * vec1.length + innerIndex] = v0 * v1; }); }); return ret; } exports.outerProduct = outerProduct; //# sourceMappingURL=../maps/lib/utils.js.map