darknet/src/dropout_layer.c

61 lines
1.6 KiB
C
Raw Permalink Normal View History

2017-06-02 06:31:13 +03:00
#include "dropout_layer.h"
#include "utils.h"
#include "cuda.h"
2014-11-19 00:51:04 +03:00
#include <stdlib.h>
#include <stdio.h>
2014-08-08 23:04:15 +04:00
2015-05-11 23:46:49 +03:00
dropout_layer make_dropout_layer(int batch, int inputs, float probability)
2014-08-08 23:04:15 +04:00
{
2015-05-11 23:46:49 +03:00
dropout_layer l = {0};
l.type = DROPOUT;
l.probability = probability;
l.inputs = inputs;
l.outputs = inputs;
l.batch = batch;
l.rand = calloc(inputs*batch, sizeof(float));
l.scale = 1./(1.-probability);
l.forward = forward_dropout_layer;
l.backward = backward_dropout_layer;
2014-12-13 23:01:21 +03:00
#ifdef GPU
l.forward_gpu = forward_dropout_layer_gpu;
l.backward_gpu = backward_dropout_layer_gpu;
2015-05-11 23:46:49 +03:00
l.rand_gpu = cuda_make_array(l.rand, inputs*batch);
2014-11-19 00:51:04 +03:00
#endif
2016-11-16 11:15:46 +03:00
fprintf(stderr, "dropout p = %.2f %4d -> %4d\n", probability, inputs, inputs);
2015-05-11 23:46:49 +03:00
return l;
2014-08-08 23:04:15 +04:00
}
2015-05-11 23:46:49 +03:00
void resize_dropout_layer(dropout_layer *l, int inputs)
2015-02-11 06:41:03 +03:00
{
2015-05-11 23:46:49 +03:00
l->rand = realloc(l->rand, l->inputs*l->batch*sizeof(float));
2015-02-11 06:41:03 +03:00
#ifdef GPU
2015-05-11 23:46:49 +03:00
cuda_free(l->rand_gpu);
2015-02-11 06:41:03 +03:00
2015-05-11 23:46:49 +03:00
l->rand_gpu = cuda_make_array(l->rand, inputs*l->batch);
2015-02-11 06:41:03 +03:00
#endif
}
void forward_dropout_layer(dropout_layer l, network net)
2014-08-08 23:04:15 +04:00
{
int i;
if (!net.train) return;
2015-05-11 23:46:49 +03:00
for(i = 0; i < l.batch * l.inputs; ++i){
2016-01-19 02:40:14 +03:00
float r = rand_uniform(0, 1);
2015-05-11 23:46:49 +03:00
l.rand[i] = r;
if(r < l.probability) net.input[i] = 0;
else net.input[i] *= l.scale;
2014-08-08 23:04:15 +04:00
}
}
2014-12-13 23:01:21 +03:00
void backward_dropout_layer(dropout_layer l, network net)
2014-08-08 23:04:15 +04:00
{
2014-12-13 23:01:21 +03:00
int i;
if(!net.delta) return;
2015-05-11 23:46:49 +03:00
for(i = 0; i < l.batch * l.inputs; ++i){
float r = l.rand[i];
if(r < l.probability) net.delta[i] = 0;
else net.delta[i] *= l.scale;
2014-12-13 23:01:21 +03:00
}
2014-08-08 23:04:15 +04:00
}
2014-11-19 00:51:04 +03:00