-
Notifications
You must be signed in to change notification settings - Fork 87
/
DeepNonLinearity.swift
191 lines (163 loc) · 5.64 KB
/
DeepNonLinearity.swift
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//
// DeepNonLinearity.swift
// AIToolbox
//
// Created by Kevin Coble on 4/13/17.
// Copyright © 2017 Kevin Coble. All rights reserved.
//
import Foundation
import Accelerate
final public class DeepNonLinearity : DeepNetworkOperator
{
public var activation : NeuralActivationFunction
var lastOutputs : [Float]
var resultSize : DeepChannelSize
public init(activation : NeuralActivationFunction)
{
self.activation = activation
self.resultSize = DeepChannelSize(dimensionCount: 0, dimensionValues: [])
lastOutputs = []
}
public init?(fromDictionary: [String: AnyObject])
{
lastOutputs = []
resultSize = DeepChannelSize(dimensionCount: 0, dimensionValues: [])
// Get the activation type
let activationTypeValue = fromDictionary["activation"] as? NSInteger
if activationTypeValue == nil { return nil }
let tempActivationType = NeuralActivationFunction(rawValue: activationTypeValue!)
if (tempActivationType == nil) { return nil }
activation = tempActivationType!
}
public func getType() -> DeepNetworkOperatorType
{
return .nonLinearityOperation
}
public func getDetails() -> String
{
return activation.getString()
}
public func getResultingSize(_ inputSize: DeepChannelSize) -> DeepChannelSize
{
return inputSize
}
public func initializeParameters()
{
// No parameters
}
public func feedForward(_ inputs: [Float], inputSize: DeepChannelSize) -> [Float]
{
// Allocate an output array
resultSize = inputSize
lastOutputs = [Float](repeating: 0.0, count: inputSize.totalSize)
// Perform the non-linearity
switch (activation) {
case .none:
lastOutputs = inputs
break
case .hyperbolicTangent:
lastOutputs = inputs.map({ tanh($0) })
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
lastOutputs = inputs.map( { 1.0 / (1.0 + exp(-$0)) } )
break
case .rectifiedLinear:
lastOutputs = inputs.map( { $0 < 0 ? 0.0 : $0 } )
break
case .softSign:
lastOutputs = inputs.map( { $0 / (1.0 + exp($0)) } )
break
case .softMax:
lastOutputs = inputs.map( { exp($0) } )
break
}
return lastOutputs
}
public func getResults() -> [Float]
{
return lastOutputs
}
public func getResultSize() -> DeepChannelSize
{
return resultSize
}
public func getResultRange() ->(minimum: Float, maximum: Float)
{
if activation == .hyperbolicTangent {
return (minimum: -1.0, maximum: 1.0)
}
return (minimum: 0.0, maximum: 1.0)
}
public func startBatch()
{
// No parameters
}
// 𝟃E/𝟃o comes in, 𝟃E/𝟃i goes out
public func backPropogateGradient(_ upStreamGradient: [Float]) -> [Float]
{
// Forward equation is o = fn(i) for each element of the input, where fn is the activation function
// The 𝟃E/𝟃o comes in, we need to calculate 𝟃E/𝟃i
// 𝟃E/𝟃i = 𝟃E/𝟃o ⋅ 𝟃o/𝟃i
// = upStreamGradient ⋅ activation'
// Allocate the downstream gradient array
var downStreamGradient = upStreamGradient
// Get 𝟃E/𝟃i for each element
switch (activation) {
case .none:
break
case .hyperbolicTangent:
for index in 0..<lastOutputs.count {
downStreamGradient[index] *= (1 - lastOutputs[index] * lastOutputs[index])
}
break
case .sigmoidWithCrossEntropy:
fallthrough
case .sigmoid:
for index in 0..<lastOutputs.count {
downStreamGradient[index] *= (lastOutputs[index] - (lastOutputs[index] * lastOutputs[index]))
}
break
case .rectifiedLinear:
for index in 0..<lastOutputs.count {
if (lastOutputs[index] < 0.0) { downStreamGradient[index] = 0.0 }
}
break
case .softSign:
var i : Float
// Reconstitute i from o
for index in 0..<lastOutputs.count {
if (lastOutputs[index] < 0) { // Negative i
i = lastOutputs[index] / (1.0 + lastOutputs[index])
downStreamGradient[index] /= -((1.0 + i) * (1.0 + i))
}
else { // Positive i
i = lastOutputs[index] / (1.0 - lastOutputs[index])
downStreamGradient[index] /= ((1.0 + i) * (1.0 + i))
}
}
break
case .softMax:
// Should not get here - softmax is not allowed except on final layer
break
}
return downStreamGradient
}
public func updateWeights(_ trainingRate : Float, weightDecay: Float)
{
// No parameters
}
public func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool
{
// No (stored) gradients in a nonlinearity operation
return true
}
public func getPersistenceDictionary() -> [String: AnyObject]
{
var resultDictionary : [String: AnyObject] = [:]
// Set the activation type
resultDictionary["activation"] = activation.rawValue as AnyObject?
return resultDictionary
}
}