C++ (Qt)#include <iostream>#include <vector>#include <boost/format.hpp>#include "tiny_dnn/tiny_dnn.h" using namespace std;using namespace tiny_dnn;using boost::format; static constexpr size_t IN_SIZE = 30; // число предыдущих шагов для определения вероятности следующего шагаstatic constexpr size_t OUT_SIZE = 2;static constexpr size_t SIZE = 2500; // Полный размер данныхstatic constexpr size_t TRAINING_SIZE = 2000; // Часть данных, для обучения сетиstatic constexpr size_t BATCH_SIZE = 10;static constexpr size_t EPOCHS = 1000; inline float toValue( bool v ){ return v? 1. : 0.;} int main( int /*argc*/, char */*argv*/[] ){ network<sequential> net; net << fully_connected_layer( IN_SIZE, 30 ) << tanh_layer() << fully_connected_layer( 30, 30 ) << tanh_layer() << fully_connected_layer( 30, OUT_SIZE ); cout << "Generate source..." << endl; vector<bool> source( SIZE ); for( size_t i = 0; i < source.size(); ++i ) source[ i ] = sin( i ) + cos( 4 * i ) >= 0; cout << "Prepare datas..." << endl; const size_t numData = TRAINING_SIZE - IN_SIZE; std::vector<vec_t> inData; inData.reserve( numData ); std::vector<vec_t> outData; outData.reserve( numData ); for( size_t i = IN_SIZE; i < TRAINING_SIZE; ++i ) { vec_t vIn( IN_SIZE ); for( size_t j = 0; j < IN_SIZE; ++j ) vIn[ j ] = toValue( source[ i - IN_SIZE + j ] ); vec_t vOut( OUT_SIZE ); vOut[ 0 ] = toValue( !source[ i ] ); vOut[ 1 ] = toValue( source[ i ] ); inData.push_back( vIn ); outData.push_back( vOut ); } int iEpoch = 0; auto on_enumerate_epoch = [&](){ if( ++iEpoch % 100 ) return; const double loss = net.get_loss<mse>( inData, outData ); cout << format( "epoch = %1%/%2% loss = %3%" ) % iEpoch % EPOCHS % loss << endl; }; cout << "Training..." << endl; adamax opt; net.fit<mse>( opt, inData, outData, BATCH_SIZE, EPOCHS, [](){}, on_enumerate_epoch ); cout << "Checking..." << endl; size_t errCnt = 0; for( size_t i = TRAINING_SIZE; i < SIZE; ++i ) { vec_t vIn( IN_SIZE ); for( size_t j = 0; j < IN_SIZE; ++j ) vIn[ j ] = toValue( source[ i - IN_SIZE + j ] ); const vec_t vOut = net.predict( vIn ); assert( vOut.size() == 2 ); const bool observed = source[ i ]; const bool predicted = vOut[ 0 ] < vOut[ 1 ]; cout << format( "i = %1%\t[%2%]\tobserved = %3%\tpredicted = %4%\t[0] = %5%\t[1] = %6%" ) % i % ((observed != predicted)? '!' : ' ') % observed % predicted % vOut[ 0 ] % vOut[ 1 ] << std::endl; if( observed != predicted ) ++errCnt; } cout << format( "Error = %1%/%2% %3%%%" ) % errCnt % (SIZE - TRAINING_SIZE) % (float( errCnt ) / float( SIZE - TRAINING_SIZE ) * 100.) << std::endl; return 0;}
C++ (Qt)sin( i ) + cos( 4 * i ) + sin( 8 * i )