-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneuralnetwork.js
75 lines (73 loc) · 2.33 KB
/
neuralnetwork.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
export class NeuralNetwork {
layers
inputNodes
/**
* @param {number} inputNeurons
* @param {number} outputNeurons
* @param {Array} shape
*
* shape: [numberOfNeuronsLayer1,numberOfNeuronsLayer2,numberOfNeuronsLayer3...]
*/
constructor(inputNeurons, shape) {
this.inputNodes = inputNeurons
let previousLayerOutputs = inputNeurons
this.layers = shape.map(neurons => {
const layer = new Layer(previousLayerOutputs, neurons)
previousLayerOutputs = neurons
return layer
})
}
run(inputs) {
let outputs = new Array(this.layers.length).fill([])
let index = 0
this.layers.forEach(layer => {
if (index == 0) {
outputs[index] = layer.calcOutputs(inputs)
} else {
outputs[index] = layer.calcOutputs(outputs[index - 1])
}
index++
})
return outputs[this.layers.length - 1]
}
loss(inputs, expectedOutputs) {
let outputs = this.run(inputs)
const outputLayer = this.layers[this.layers.length - 1]
let loss = 0
for (let i = 0; i < outputs.length; i++) {
loss += outputLayer.neuronCost(outputs[i], expectedOutputs[i])
}
return loss
}
}
export class Layer {
inputNodes = undefined
outputNodes = undefined
weights = [] // 2-dimensional
biases = [] // 1-dim
constructor(inputNeurons, outputNeurons) {
this.inputNodes = inputNeurons
this.outputNodes = outputNeurons
this.biases = new Array(outputNeurons).fill(0)
this.weights = new Array(outputNeurons).fill([])
}
calcOutputs(inputs) {
let activations = []
//loop through output neurons
for (let i = 0; i < this.outputNodes; i++) {
let weightedInput = this.biases[i]
//loop through input neurons
for (let x = 0; x < this.inputNodes; x++) {
console.log(this.weights)
weightedInput += inputs[x] * this.weights[x, i]
}
activations[i] = sigmoid(weightedInput)
}
return activations
}
neuronCost(activation, expected) {
let error = activation - expected
return error * error
}
}
const sigmoid = (x) => 1 / (1 + Math.exp(-x))