Class TNeuronalNetwork: simplifying the TensorFlow code

Class TNeuronalNetwork: simplifying the TensorFlow code

Postby Antonio Linares » Wed Aug 16, 2017 8:34 am

When we review the TensorFlow examples we notice a lot of repetitive code.

That reminds me the Windows Petzold's era, so again we can simplify the repetitive code,
creating a generic class TNeuronalNetWork in Python :-)

This is a work in progress, very good to learn basic Python stuff!

class.py
Code: Select all  Expand view
import tensorflow as tf

class TPerceptron :
   aWeights = []

   def New( self, nInputs ) :
      for n in range( nInputs ) :
         self.aWeights.append( tf.zeros( [] ) )

class TLayer :
   aPerceptrons = []
   bias = None
   aPrevLayer = None

   def New( self, nPerceptrons ) :
      for n in range( nPerceptrons ) :
         if self.aPrevLayer :
            self.aPerceptrons.append( TPerceptron().New( len( self.aPrevLayer.aPerceptrons ) ) )
         else :
            self.aPerceptrons.append( TPerceptron().New( 0 ) )
      self.bias = tf.zeros( [] )
      return self     

class TNeuronalNetwork :   
   aLayers = []    
   input = None
   output = None
   nLearningRate = 0.002
   nTrainingEpochs = 500
   tf = None
   loss = None
   optimizer = None

   def New( self, aTopology ) :
      self.input = tf.placeholder( "float", shape=( None, aTopology[ 0 ] ) )
      self.output = tf.placeholder( "float", shape=( None, aTopology[ -1 ] ) )
       
      for n in range( len( aTopology ) ) :
         self.aLayers.append( [] )
         self.aLayers[ -1 ] = TLayer().New( aTopology[ n ] )
         
         if n == 0 :
            self.tf = tf.add( tf.matmul( self.input, weights[ 'h1' ] ), self.aLayers[ -1 ].bias )
         else :
            self.aLayers[ -1 ].aPrevLayer = self.aLayers[ -2 ]            
            self.tf = tf.add( tf.matmul( self.tf, weights[ 'h1' ] ), self.aLayers[ -1 ].bias )

         self.loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits=self.tf, labels=self.output ) )
         self.optimizer = tf.train.AdamOptimizer( learning_rate = self.nLearningRate ).minimize( self.loss )
      return self

oNN = TNeuronalNetwork().New( [ 5, 7, 1 ] )
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
 
Posts: 42081
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain

Re: Class TNeuronalNetwork: simplifying the TensorFlow code

Postby Antonio Linares » Wed Aug 23, 2017 1:12 pm

We better go step by step to implement it:

viewtopic.php?p=204899#p204899
regards, saludos

Antonio Linares
www.fivetechsoft.com
User avatar
Antonio Linares
Site Admin
 
Posts: 42081
Joined: Thu Oct 06, 2005 5:47 pm
Location: Spain


Return to Artificial Intelligence examples

Who is online

Users browsing this forum: No registered users and 3 guests

cron