forked from trekhleb/micrograd-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnn.ts
83 lines (71 loc) · 1.78 KB
/
nn.ts
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
76
77
78
79
80
81
82
83
import { Value } from './engine'
class Module {
zeroGrad() {
for (const p of this.parameters()) p.grad = 0
}
parameters(): Value[] {
return []
}
}
export class Neuron extends Module {
w: Value[] = []
b: Value
constructor(nin: number) {
super()
for (let i = 0; i < nin; i++) {
const wi = new Value(Math.random() * 2 - 1)
this.w.push(wi)
}
this.b = new Value(Math.random() * 2 - 1)
}
// w * x + b
forward(x: Value[]): Value {
if (!x.length) throw new Error('Empty x')
let act = x[0].mul(this.w[0])
for (let i = 1; i < x.length; i++) {
act = act.add(x[i].mul(this.w[i]))
}
act = act.add(this.b)
return act.tanh()
}
parameters(): Value[] {
return [...this.w, this.b]
}
}
export class Layer extends Module {
neurons: Neuron[] = []
constructor(nin: number, nout: number) {
super()
for (let i = 0; i < nout; i++) this.neurons.push(new Neuron(nin))
}
forward(x: Value[]): Value[] {
const outs: Value[] = []
for (const neuron of this.neurons) outs.push(neuron.forward(x))
return outs
}
parameters(): Value[] {
const params: Value[] = []
for (const neuron of this.neurons) params.push(...neuron.parameters())
return params
}
}
export class MLP extends Module {
layers: Layer[] = []
constructor(nin: number, nouts: number[]) {
super()
const sz = [nin, ...nouts]
for (let i = 0; i < nouts.length; i++) {
this.layers.push(new Layer(sz[i], sz[i + 1]))
}
}
forward(xin: Value[]): Value[] {
let xout = [...xin]
for (const layer of this.layers) xout = layer.forward(xout)
return xout
}
parameters(): Value[] {
const params: Value[] = []
for (const layer of this.layers) params.push(...layer.parameters())
return params
}
}