neural network the code train
by Mladen Mihajlovic
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>
JavaScript
class Matrix {
constructor(rows, cols) {
this.rows = rows;
this.cols = cols;
this.data = [];
for (var i = 0; i < this.rows; i++) {
this.data[i] = [];
for (var j = 0; j < this.cols; j++) {
this.data[i][j] = 0;
} //for cols
} //for rows
} //data
static fromArray(arr) {
let m = new Matrix(arr.length, 1);
for (let i = 0; i < arr.length; i++) {
m.data[i][0] = arr[i];
}
return m;
}
static subtract(a, b) {
let result = new Matrix(a.rows, a.cols);
for (var i = 0; i < result.rows; i++) {
for (var j = 0; j < result.cols; j++) {
result.data[i][j] = a.data[i][j] - b.data[i][j];
}
}
return result;
}
toArray() {
let arr = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) {
arr.push(this.data[i][j]);
}
}
return arr;
}
randomize() {
this.map((v) => Math.random() * 2 - 1);
}
add(n) {
if (n instanceof Matrix) {
this.map((v, r, c) => v + n.data[r][c]);
} else {
this.map((v, r, c) => v + n);
}
}
static transpose(m) {
let result = new Matrix(m.cols, m.rows);
for (var i = 0; i < m.rows; i++) {
for (var j = 0; j < m.cols; j++) {
result.data[j][i] = m.data[i][j];
} //for cols
} //for rows
return result;
}
static multiply(a, b) {
//Matrix product
if (a.cols !== b.rows) {
console.log("Cols of a must match rows of b");
return undefined;
}
let result = new Matrix(a.rows, b.cols);
for (let i = 0; i < result.rows; i++) {
for (let j = 0; j < result.cols; j++) {
//dot product
let sum = 0;
for (let k = 0; k < a.cols; k++) {
sum += a.data[i][k] * b.data[k][j];
}
result.data[i][j] = sum;
} //for cols
} //for rows
return result;
}
multiply(n) {
//Scalar product
this.map((v, r, c) => v *= n);
}
map(fn) {
...