xxxxxxxxxx
92
let weights = [];
let width = 1200;
let height = 600;
let training
let output
//let b = 0.1; //Bias
let n = 16; //Number of pixels
let N = 1000 //Training iterations
let η = 0.5; //Learning rate
function setup() {
createCanvas(width, height);
for (let i = 0; i < n; i++) {
let temp = [];
for (let j = 0; j < n; j++) {
temp.push(1 / n);
}
weights.push(temp);
}
calc = createButton("Train");
calc.mousePressed(train);
//Training for N iterations
for (let i = 0; i < N; i++) {
train();
}
}
function draw() {
background(220);
//This creates the image of the machine output
for (let i = 0; i < sqrt(n); i++) {
for (let j = 0; j < sqrt(n); j++) {
fill(output[i + 4 * j] * 255);
rect(
(i * width) / sqrt(n) / 2,
(j * height) / sqrt(n),
((i + 1) * width) / sqrt(n) / 2,
((j + 1) * height) / sqrt(n)
);
}
}
//This draws the training image
for (let i = 0; i < sqrt(n); i++) {
for (let j = 0; j < sqrt(n); j++) {
fill(training[i + 4 * j] * 255);
rect(
((i + 4) * width) / sqrt(n) / 2,
(j * height) / sqrt(n),
((i + 5) * width) / sqrt(n) / 2,
((j + 1) * height) / sqrt(n)
);
}
}
}
//This trains the machine and adjusts the weights on a random training image
function train() {
//Here I create a new random training image
training = [];
for (let i = 0; i < n; i++) {
training.push(round(random()));
}
output = matMul(weights, training);
//Here I adjust the weights according to the output and the expected output(training)
for (let i = 0; i < weights.length; i++) {
for (let j = 0; j < weights[i].length; j++) {
weights[i][j] +=
(training[i] - output[i])*output[j]*(1-output[j])*training[j]* η;
}
}
print(weights)
//print(output)
}
//This is the scalar product to calculate each pixel of the output picture
function dot(v, w) {
let S = 0;
for (let i = 0; i < v.length; i++) {
S += v[i] * w[i];
}
return S;
}
//This performs all the scalar products, takes the sigmoid on the result and produces the total image
function matMul(A, x) {
let S = [];
for (let i = 0; i < A.length; i++) {
S.push(sigmoid(dot(A[i], x)));
}
return S;
}
//The sigmoid function makes sure our values are between 0 and 1
function sigmoid(x) {
return 1 / (1 + exp(-x));
}