summaryrefslogtreecommitdiff
path: root/src/main/java/org/apache/commons/math3/ml/neuralnet/Neuron.java
blob: 8cae3ea53aafe5e174df25b6026851ee41400d00 (plain)
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.math3.ml.neuralnet;

import java.io.Serializable;
import java.io.ObjectInputStream;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.util.Precision;


/**
 * Describes a neuron element of a neural network.
 *
 * This class aims to be thread-safe.
 *
 * @since 3.3
 */
public class Neuron implements Serializable {
    /** Serializable. */
    private static final long serialVersionUID = 20130207L;
    /** Identifier. */
    private final long identifier;
    /** Length of the feature set. */
    private final int size;
    /** Neuron data. */
    private final AtomicReference<double[]> features;
    /** Number of attempts to update a neuron. */
    private final AtomicLong numberOfAttemptedUpdates = new AtomicLong(0);
    /** Number of successful updates  of a neuron. */
    private final AtomicLong numberOfSuccessfulUpdates = new AtomicLong(0);

    /**
     * Creates a neuron.
     * The size of the feature set is fixed to the length of the given
     * argument.
     * <br/>
     * Constructor is package-private: Neurons must be
     * {@link Network#createNeuron(double[]) created} by the network
     * instance to which they will belong.
     *
     * @param identifier Identifier (assigned by the {@link Network}).
     * @param features Initial values of the feature set.
     */
    Neuron(long identifier,
           double[] features) {
        this.identifier = identifier;
        this.size = features.length;
        this.features = new AtomicReference<double[]>(features.clone());
    }

    /**
     * Performs a deep copy of this instance.
     * Upon return, the copied and original instances will be independent:
     * Updating one will not affect the other.
     *
     * @return a new instance with the same state as this instance.
     * @since 3.6
     */
    public synchronized Neuron copy() {
        final Neuron copy = new Neuron(getIdentifier(),
                                       getFeatures());
        copy.numberOfAttemptedUpdates.set(numberOfAttemptedUpdates.get());
        copy.numberOfSuccessfulUpdates.set(numberOfSuccessfulUpdates.get());

        return copy;
    }

    /**
     * Gets the neuron's identifier.
     *
     * @return the identifier.
     */
    public long getIdentifier() {
        return identifier;
    }

    /**
     * Gets the length of the feature set.
     *
     * @return the number of features.
     */
    public int getSize() {
        return size;
    }

    /**
     * Gets the neuron's features.
     *
     * @return a copy of the neuron's features.
     */
    public double[] getFeatures() {
        return features.get().clone();
    }

    /**
     * Tries to atomically update the neuron's features.
     * Update will be performed only if the expected values match the
     * current values.<br/>
     * In effect, when concurrent threads call this method, the state
     * could be modified by one, so that it does not correspond to the
     * the state assumed by another.
     * Typically, a caller {@link #getFeatures() retrieves the current state},
     * and uses it to compute the new state.
     * During this computation, another thread might have done the same
     * thing, and updated the state: If the current thread were to proceed
     * with its own update, it would overwrite the new state (which might
     * already have been used by yet other threads).
     * To prevent this, the method does not perform the update when a
     * concurrent modification has been detected, and returns {@code false}.
     * When this happens, the caller should fetch the new current state,
     * redo its computation, and call this method again.
     *
     * @param expect Current values of the features, as assumed by the caller.
     * Update will never succeed if the contents of this array does not match
     * the values returned by {@link #getFeatures()}.
     * @param update Features's new values.
     * @return {@code true} if the update was successful, {@code false}
     * otherwise.
     * @throws DimensionMismatchException if the length of {@code update} is
     * not the same as specified in the {@link #Neuron(long,double[])
     * constructor}.
     */
    public boolean compareAndSetFeatures(double[] expect,
                                         double[] update) {
        if (update.length != size) {
            throw new DimensionMismatchException(update.length, size);
        }

        // Get the internal reference. Note that this must not be a copy;
        // otherwise the "compareAndSet" below will always fail.
        final double[] current = features.get();
        if (!containSameValues(current, expect)) {
            // Some other thread already modified the state.
            return false;
        }

        // Increment attempt counter.
        numberOfAttemptedUpdates.incrementAndGet();

        if (features.compareAndSet(current, update.clone())) {
            // The current thread could atomically update the state (attempt succeeded).
            numberOfSuccessfulUpdates.incrementAndGet();
            return true;
        } else {
            // Some other thread came first (attempt failed).
            return false;
        }
    }

    /**
     * Retrieves the number of calls to the
     * {@link #compareAndSetFeatures(double[],double[]) compareAndSetFeatures}
     * method.
     * Note that if the caller wants to use this method in combination with
     * {@link #getNumberOfSuccessfulUpdates()}, additional synchronization
     * may be required to ensure consistency.
     *
     * @return the number of update attempts.
     * @since 3.6
     */
    public long getNumberOfAttemptedUpdates() {
        return numberOfAttemptedUpdates.get();
    }

    /**
     * Retrieves the number of successful calls to the
     * {@link #compareAndSetFeatures(double[],double[]) compareAndSetFeatures}
     * method.
     * Note that if the caller wants to use this method in combination with
     * {@link #getNumberOfAttemptedUpdates()}, additional synchronization
     * may be required to ensure consistency.
     *
     * @return the number of successful updates.
     * @since 3.6
     */
    public long getNumberOfSuccessfulUpdates() {
        return numberOfSuccessfulUpdates.get();
    }

    /**
     * Checks whether the contents of both arrays is the same.
     *
     * @param current Current values.
     * @param expect Expected values.
     * @throws DimensionMismatchException if the length of {@code expected}
     * is not the same as specified in the {@link #Neuron(long,double[])
     * constructor}.
     * @return {@code true} if the arrays contain the same values.
     */
    private boolean containSameValues(double[] current,
                                      double[] expect) {
        if (expect.length != size) {
            throw new DimensionMismatchException(expect.length, size);
        }

        for (int i = 0; i < size; i++) {
            if (!Precision.equals(current[i], expect[i])) {
                return false;
            }
        }
        return true;
    }

    /**
     * Prevents proxy bypass.
     *
     * @param in Input stream.
     */
    private void readObject(ObjectInputStream in) {
        throw new IllegalStateException();
    }

    /**
     * Custom serialization.
     *
     * @return the proxy instance that will be actually serialized.
     */
    private Object writeReplace() {
        return new SerializationProxy(identifier,
                                      features.get());
    }

    /**
     * Serialization.
     */
    private static class SerializationProxy implements Serializable {
        /** Serializable. */
        private static final long serialVersionUID = 20130207L;
        /** Features. */
        private final double[] features;
        /** Identifier. */
        private final long identifier;

        /**
         * @param identifier Identifier.
         * @param features Features.
         */
        SerializationProxy(long identifier,
                           double[] features) {
            this.identifier = identifier;
            this.features = features;
        }

        /**
         * Custom serialization.
         *
         * @return the {@link Neuron} for which this instance is the proxy.
         */
        private Object readResolve() {
            return new Neuron(identifier,
                              features);
        }
    }
}