@@ -43,6 +43,58 @@ public static Tensor bias_add(Tensor value,
4343 } ) ;
4444 }
4545
46+ /// <summary>
47+ /// Computes dropout.
48+ /// </summary>
49+ /// <param name="x"></param>
50+ /// <param name="rate"></param>
51+ /// <param name="noise_shape"></param>
52+ /// <param name="seed"></param>
53+ /// <param name="name"></param>
54+ /// <returns></returns>
55+ public static Tensor dropout_v2 ( Tensor x , Tensor rate , Tensor noise_shape = null , int ? seed = null , string name = null )
56+ {
57+ return with ( ops . name_scope ( name , "dropout" , x ) , scope =>
58+ {
59+ name = scope ;
60+ x = ops . convert_to_tensor ( x , name : "x" ) ;
61+ if ( ! x . dtype . is_floating ( ) )
62+ throw new NotImplementedException ( $ "x has to be a floating point tensor since it's going to" +
63+ $ " be scaled. Got a { x . dtype } tensor instead.") ;
64+
65+ rate = ops . convert_to_tensor ( rate , dtype : x . dtype , name : "rate" ) ;
66+ // Do nothing if we know rate == 0
67+ var val = tensor_util . constant_value ( rate ) ;
68+ if ( ! ( val is null ) && val . Data < float > ( 0 ) == 0 )
69+ return x ;
70+
71+ noise_shape = _get_noise_shape ( x , noise_shape ) ;
72+
73+ // Sample a uniform distribution on [0.0, 1.0) and select values larger than
74+ // rate.
75+ //
76+ // NOTE: Random uniform actually can only generate 2^23 floats on [1.0, 2.0)
77+ // and subtract 1.0.
78+ var random_tensor = random_ops . random_uniform ( noise_shape , seed : seed , dtype : x . dtype ) ;
79+ var keep_prob = 1.0f - rate ;
80+ var scale = 1.0f / keep_prob ;
81+ // NOTE: if (1.0 + rate) - 1 is equal to rate, then we want to consider that
82+ // float to be selected, hence we use a >= comparison.
83+ var keep_mask = random_tensor >= rate ;
84+ var ret = x * scale * math_ops . cast ( keep_mask , x . dtype ) ;
85+ ret . SetShape ( x . GetShape ( ) ) ;
86+ return ret ;
87+ } ) ;
88+ }
89+
90+ private static Tensor _get_noise_shape ( Tensor x , Tensor noise_shape )
91+ {
92+ if ( noise_shape == null )
93+ return array_ops . shape ( x ) ;
94+ else
95+ return noise_shape ;
96+ }
97+
4698 public static Tensor log_softmax ( Tensor logits , int axis = - 1 , string name = null )
4799 {
48100 return _softmax ( logits , gen_nn_ops . log_softmax , axis , name ) ;
0 commit comments