xxxxxxxxxx
123
let data;
function preload(){
data = loadJSON("./data.json");
}
class Location{
constructor(x,y,nx,ny,c,t){
this.x = x;
this.y = y;
this.nx = nx;
this.ny = ny
this.c = c;
this.t = t;
this.hasCase = this.c > 0 ? 1 : 0;
}
display(){
push();
noStroke();
if (this.c == 0 ) {
fill(0);
} else {
fill(200,0,0);
}
if (this.t == 'known'){
ellipse(this.x, this.y, 8, 8);
} else {
rectMode(CENTER)
rect(this.x, this.y, 8, 8);
}
pop();
}
}
class Neuron{
constructor(n){
this.weights = [];
this.learningRate = 0.001;
while(this.weights.length < n + 1){
this.weights.push(random(-1,1));
}
}
train(inputs, label){
let res = this.classify(inputs);
let g = label - res;
if ( g!=0 ) {
for (let i = 0; i < this.weights.length; i ++){
this.weights[i] += g * inputs[i] * this.learningRate;
// direction(g & inputs[i]) * how much to adjust(learningRate);
}
errorNo ++;
}
}
classify(inputs){
let raw = 0;
inputs.forEach((i,idx) => {
raw += i*this.weights[idx];
});
return this.activation(raw);
}
activation(raw){
return raw > 0 ? 1 : 0;
}
}
let locations = [];
let errorNo;
function setup() {
// stupid p5
let array = [];
for (const e in data) {
array.push(data[e]);
}
data = array;
createCanvas(600, 600);
data.forEach(l => {
let x = map(l.long,-180,180,0,width);
let y = map(l.lat,-90,90,0,height);
let nx = map(l.long,-180,180,-1,1);
let ny = map(l.lat,-90,90,-1,1);
let tem = new Location(x,y,nx,ny,l.cases,'known');
locations.push(tem);
});
neuron = new Neuron(2);
bias = 1;
//noLoop();
}
function draw(){
background(255)
if (errorNo != 0) {
errorNo = 0;
locations.forEach(l => {
if(l.t == 'known') neuron.train([l.nx, l.ny, bias], l.hasCase);
l.display();
//train 1 iteration
});
} else {
locations.forEach(l => {
l.display();
//just display
});
}
text(errorNo + " <- when it become 0, click to add new location that you want to classify, the added ones will be shown as squres.",5,5, width, 50);
line(0,map((neuron.weights[0] - neuron.weights[2])/neuron.weights[1], -1, 1, 0, height), width, map(-1*(neuron.weights[0] + neuron.weights[2])/neuron.weights[1], -1, 1, 0, height));
// drawing this line is the hardest lol
}
function mouseClicked(){
if (errorNo < 5) {
let nx = map(mouseX, 0, width, -1, 1);
let ny = map(mouseY, 0, height, -1, 1);
locations.push(new Location(mouseX, mouseY, nx, ny, neuron.classify([nx,ny,bias]), 'unknown'));
}
}