1
+ namespace AiDotNet . ActivationFunctions ;
2
+
3
+ public class SignActivation < T > : ActivationFunctionBase < T >
4
+ {
5
+ protected override bool SupportsScalarOperations ( ) => true ;
6
+
7
+ public override T Activate ( T input )
8
+ {
9
+ if ( NumOps . LessThan ( input , NumOps . Zero ) )
10
+ return NumOps . FromDouble ( - 1 ) ;
11
+ else if ( NumOps . GreaterThan ( input , NumOps . Zero ) )
12
+ return NumOps . One ;
13
+ else
14
+ return NumOps . Zero ;
15
+ }
16
+
17
+ public override T Derivative ( T input )
18
+ {
19
+ // The derivative of the sign function is 0 everywhere except at 0,
20
+ // where it's undefined. We'll return 0 for all inputs.
21
+ return NumOps . Zero ;
22
+ }
23
+
24
+ public override Vector < T > Activate ( Vector < T > input )
25
+ {
26
+ Vector < T > output = new Vector < T > ( input . Length ) ;
27
+ for ( int i = 0 ; i < input . Length ; i ++ )
28
+ {
29
+ output [ i ] = Activate ( input [ i ] ) ;
30
+ }
31
+
32
+ return output ;
33
+ }
34
+
35
+ public override Matrix < T > Derivative ( Vector < T > input )
36
+ {
37
+ int n = input . Length ;
38
+ Matrix < T > jacobian = new Matrix < T > ( n , n ) ;
39
+ // The Jacobian matrix will be all zeros
40
+ for ( int i = 0 ; i < n ; i ++ )
41
+ {
42
+ for ( int j = 0 ; j < n ; j ++ )
43
+ {
44
+ jacobian [ i , j ] = NumOps . Zero ;
45
+ }
46
+ }
47
+
48
+ return jacobian ;
49
+ }
50
+
51
+ public override Tensor < T > Activate ( Tensor < T > input )
52
+ {
53
+ Tensor < T > output = new Tensor < T > ( input . Shape ) ;
54
+ int totalElements = input . Shape . Aggregate ( 1 , ( a , b ) => a * b ) ;
55
+
56
+ for ( int i = 0 ; i < totalElements ; i ++ )
57
+ {
58
+ output [ i ] = Activate ( input [ i ] ) ;
59
+ }
60
+
61
+ return output ;
62
+ }
63
+
64
+ public override Tensor < T > Derivative ( Tensor < T > input )
65
+ {
66
+ int [ ] outputShape = new int [ input . Shape . Length + 1 ] ;
67
+ Array . Copy ( input . Shape , outputShape , input . Shape . Length ) ;
68
+ outputShape [ outputShape . Length - 1 ] = input . Shape [ input . Shape . Length - 1 ] ;
69
+
70
+ Tensor < T > output = new Tensor < T > ( outputShape ) ;
71
+ int batchSize = input . Shape [ 0 ] ;
72
+ int vectorLength = input . Shape [ 1 ] ;
73
+
74
+ for ( int i = 0 ; i < batchSize ; i ++ )
75
+ {
76
+ Vector < T > vector = new Vector < T > ( vectorLength ) ;
77
+ for ( int j = 0 ; j < vectorLength ; j ++ )
78
+ {
79
+ vector [ j ] = input [ i , j ] ;
80
+ }
81
+
82
+ Matrix < T > jacobian = Derivative ( vector ) ;
83
+
84
+ for ( int j = 0 ; j < vectorLength ; j ++ )
85
+ {
86
+ for ( int k = 0 ; k < vectorLength ; k ++ )
87
+ {
88
+ output [ i , j , k ] = jacobian [ j , k ] ;
89
+ }
90
+ }
91
+ }
92
+
93
+ return output ;
94
+ }
95
+ }
0 commit comments