This repository was archived by the owner on Feb 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDropout.cs
More file actions
77 lines (62 loc) · 2.13 KB
/
Copy pathDropout.cs
File metadata and controls
77 lines (62 loc) · 2.13 KB
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
namespace NeuralNetwork;
[Serializable]
public unsafe class Dropout : Layer
{
private readonly ushort dropoutRate;
private readonly float dropoutRateFloat;
private readonly float qCoeff, invDropoutRateFloat;
private readonly Random rndDropout;
private bool[] dropped;
public Dropout(float dropoutRate, string name = null) : base(name)
{
this.dropoutRateFloat = (float)Math.Round(dropoutRate, 3);
this.dropoutRate = (ushort)(1000 * dropoutRateFloat);
this.invDropoutRateFloat = (1 - dropoutRateFloat);
this.qCoeff = 1 / invDropoutRateFloat;
rndDropout = new Random();
}
public sealed override void Init(Optimizer optimizer)
{
outputShape = inputShape;
input = new Tensor(inputShape);
outputDerivatives = new Tensor(outputShape);
dropped = new bool[inputShape.nF1];
}
public sealed override void Forward(Tensor input, in int actualMBSize, in bool training)
{
input.CopyTo(this.input);
if (!training)
{
for (int batch = 0; batch < actualMBSize; batch++)
{
for (int flat = 0; flat < inputShape.nF1; flat++)
this.input[batch, flat] *= invDropoutRateFloat;
}
}
else
{
for (int i = 0; i < dropped.Length; i++)
dropped[i] = rndDropout.Next(1000) < dropoutRate;
for (int batch = 0; batch < actualMBSize; batch++)
{
Drop(this.input, in batch);
}
}
nextLayer.Forward(this.input, in actualMBSize, in training);
}
public sealed override void BackProp(Tensor deriv, in int actualMBSize)
{
deriv.CopyTo(outputDerivatives);
for (int batch = 0; batch < actualMBSize; batch++)
{
Drop(outputDerivatives, in batch);
}
prevLayer.BackProp(outputDerivatives, in actualMBSize);
}
public void Drop(Tensor input, in int batch)
{
for (int i = 0; i < inputShape.nF1; i++)
if (dropped[i]) input[batch, i] = 0;
else input[batch, i] *= qCoeff;
}
}