1111@interface KRHebbian ()
1212
1313@property (nonatomic , assign ) NSInteger iteration;
14+ @property (nonatomic , assign ) float lastDeltaSummation; // 上一次的權重總變化量
15+ @property (nonatomic , assign ) float deltaSummation; // 當前的權重總給化量
1416
1517@end
1618
@@ -59,7 +61,7 @@ -(double)_fOfNetWithInputs:(NSArray *)_inputs
5961}
6062
6163/*
62- * @ Step 3. 求 delta W (下一節點之權重值)
64+ * @ Step 3. 求 New Weights
6365 */
6466-(void )_turningWeightsByInputs : (NSArray *)_inputs
6567{
@@ -70,10 +72,11 @@ -(void)_turningWeightsByInputs:(NSArray *)_inputs
7072 NSInteger _index = 0 ;
7173 for ( NSNumber *_weightValue in _weights )
7274 {
73- double _deltaWeight = ( _learningRate * _netOutput * [[_inputs objectAtIndex: _index] doubleValue ] );
74- double _newWeight = [_weightValue floatValue ] + _deltaWeight;
75+ double _deltaWeight = ( _learningRate * _netOutput * [[_inputs objectAtIndex: _index] doubleValue ] );
76+ double _newWeight = [_weightValue floatValue ] + _deltaWeight;
7577 [_newWeights addObject: [NSNumber numberWithDouble: _newWeight]];
7678 ++_index;
79+ self.deltaSummation += fabs (_deltaWeight);
7780 }
7881 [self .weights removeAllObjects ];
7982 [self .weights addObjectsFromArray: _newWeights];
@@ -98,14 +101,16 @@ -(instancetype)init
98101 self = [super init ];
99102 if ( self )
100103 {
101- _learningRate = 0 .5f ;
102- _weights = [NSMutableArray new ];
103- _patterns = [NSMutableArray new ];
104+ _learningRate = 0 .5f ;
105+ _weights = [NSMutableArray new ];
106+ _patterns = [NSMutableArray new ];
104107
105- _iteration = 0 ;
106- _maxIteration = 1 ;
108+ _iteration = 0 ;
109+ _maxIteration = 1 ;
110+ _convergenceValue = 0 .0f ;
107111
108- _activeFunction = KRHebbianActiveFunctionBySgn;
112+ _activeFunction = KRHebbianActiveFunctionBySgn;
113+ _deltaSummation = 0 .0f ;
109114 }
110115 return self;
111116}
@@ -127,13 +132,20 @@ -(void)initializeWeights:(NSArray *)_initWeights
127132
128133-(void )training
129134{
135+ _lastDeltaSummation = _deltaSummation;
136+ _deltaSummation = 0 .0f ;
130137 ++_iteration;
131138 for ( NSArray *_inputs in _patterns )
132139 {
133140 [self _turningWeightsByInputs: _inputs];
134141 }
135142
136- if ( _iteration >= _maxIteration )
143+ /*
144+ * @ 收斂方法 (擇一)
145+ * - 1. 迭代數達到最大數 (文獻推薦 1 迭代)
146+ * - 2. 前後迭代的權重變化量相減,小於等於收斂值或為 0 (Optimized method by me, but not usefully in normal cases)
147+ */
148+ if ( _iteration >= _maxIteration || fabsf (_deltaSummation - _lastDeltaSummation) <= _convergenceValue )
137149 {
138150 if ( nil != _trainingCompletion )
139151 {
0 commit comments