You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.6 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "dropout_layer.h"
  2. #include "utils.h"
  3. #include "dn_cuda.h"
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. namespace DN{
  7. dropout_layer make_dropout_layer(int batch, int inputs, float probability)
  8. {
  9. dropout_layer l;
  10. memset(&l, 0, sizeof(dropout_layer));
  11. l.type = DROPOUT;
  12. l.probability = probability;
  13. l.inputs = inputs;
  14. l.outputs = inputs;
  15. l.batch = batch;
  16. l.rand = (float*)calloc(inputs*batch, sizeof(float));
  17. l.scale = (float)(1. / (1. - probability));
  18. l.forward = forward_dropout_layer;
  19. l.backward = backward_dropout_layer;
  20. #ifdef GPU
  21. l.forward_gpu = forward_dropout_layer_gpu;
  22. l.backward_gpu = backward_dropout_layer_gpu;
  23. l.rand_gpu = cuda_make_array(l.rand, inputs*batch);
  24. #endif
  25. fprintf(stderr, "dropout p = %.2f %4d -> %4d\n", probability, inputs, inputs);
  26. return l;
  27. }
  28. void resize_dropout_layer(dropout_layer *l, int inputs)
  29. {
  30. l->rand = (float*)realloc(l->rand, l->inputs*l->batch*sizeof(float));
  31. #ifdef GPU
  32. cuda_free(l->rand_gpu);
  33. l->rand_gpu = cuda_make_array(l->rand, inputs*l->batch);
  34. #endif
  35. }
  36. void forward_dropout_layer(dropout_layer l, network net)
  37. {
  38. int i;
  39. if (!net.train) return;
  40. for (i = 0; i < l.batch * l.inputs; ++i){
  41. float r = rand_uniform(0, 1);
  42. l.rand[i] = r;
  43. if (r < l.probability) net.input[i] = 0;
  44. else net.input[i] *= l.scale;
  45. }
  46. }
  47. void backward_dropout_layer(dropout_layer l, network net)
  48. {
  49. int i;
  50. if (!net.delta) return;
  51. for (i = 0; i < l.batch * l.inputs; ++i){
  52. float r = l.rand[i];
  53. if (r < l.probability) net.delta[i] = 0;
  54. else net.delta[i] *= l.scale;
  55. }
  56. }
  57. };