00001
00002
00003 #ifndef FFNET_H
00004 #define FFNET_H
00005
00006 #include "Object.h"
00007 #include "FFLayer.h"
00008 #include <vector>
00009 #include <iostream>
00010 #include "Array.h"
00011
00012 namespace FD {
00013
00014 class TrainingAlgo;
00015
00016
00020 class FFNet : public Object {
00021 protected:
00022
00024 Vector<int> topo;
00025
00027 Vector<RCPtr<FFLayer> > layers;
00028
00030 float *weights;
00031
00033 int nbNeurons;
00034
00036 int nbWeights;
00037
00038 public:
00039 FFNet(const Vector<int> &_topo, const Vector<std::string> &functions);
00040
00041 FFNet() {}
00042
00043 FFNet(FFNet &net);
00044
00045 FFNet(const Vector<int> &_topo, const Vector<std::string> &functions, std::vector<float *> &tin, std::vector<float *> &tout);
00046
00047 void init(const Vector<std::string> &functions);
00048
00049 void setupLayersAfterRead();
00050
00052 float *calc(const float *input, float *value, float *deriv=NULL)
00053 {
00054 layers[0]->update(input, value, deriv);
00055 for (int i=1;i<layers.size();i++)
00056 {
00057 if (deriv)
00058 {
00059 layers[i]->update(value+layers[i-1]->getNeuronOffset(),
00060 value+layers[i]->getNeuronOffset(),
00061 deriv+layers[i]->getNeuronOffset());
00062 } else {
00063 layers[i]->update(value+layers[i-1]->getNeuronOffset(),
00064 value+layers[i]->getNeuronOffset());
00065 }
00066 }
00067 return value+layers[layers.size()-1]->getNeuronOffset();
00068 }
00069
00071 void learn(float *input, float *output, double *gradient, double *err=NULL, float *calc_output=NULL);
00072
00074 void calcGradient(std::vector<float *> &tin, std::vector<float *> &tout, Array<float> weights,
00075 Array<double> &gradient, double &err);
00076
00078 void weightedLearn(float *input, float *output, float *learnWeights, double *gradient,
00079 double *err=NULL, float *calc_output=NULL);
00080
00082 void weightedCalcGradient(std::vector<float *> &tin, std::vector<float *> &tout, std::vector<float *> &learnWeights,
00083 Array<float> weights, Array<double> &gradient, double &err);
00084
00086 float totalError(std::vector<float *> tin, std::vector<float *> tout);
00087
00088 int getNbWeights () {return nbWeights;}
00089
00090 int getNbNeurons () {return nbNeurons;}
00091
00092 const Vector<int> &getTopo() {return topo;}
00093
00094 const Vector<RCPtr<FFLayer> > &getLayers() {return layers;}
00095
00096 const float *getWeights() {return weights;}
00097
00098 void setWeights(float *ptr) {vec_copy(ptr, weights, nbWeights);}
00099
00100 void setDerivOffset(float d);
00101
00103 void printOn(std::ostream &out) const;
00104
00106 void readFrom (std::istream &in);
00107
00108 };
00109
00110 std::istream &operator >> (std::istream &in, FFNet &net);
00111
00112 }
00113 #endif