提问者:小点点

一个TensorFlow简单的例子


我正在尝试运行这个TensorFlow示例。似乎我使用的占位符不正确。运行时错误信息对新手没有太大帮助:-)

# Building a neuronal network with TensorFlow

import tensorflow as tf

def multilayer_perceptron( x, weights, biases ):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_1, weights['out']) + biases['out']
    return out_layer

session = tf.Session()

nInputs = 7  # Number of inputs to the neuronal network
nHiddenPerceptrons = 5
nTypes = 10  # seven posible types of values in the output
nLearningRate = 0.001
nTrainingEpochs = 15

aInputs = [ [ 1, 1, 1, 0, 1, 1, 1 ],  # zero                 2
            [ 1, 0, 0, 0, 0, 0, 1 ],  # one               ------- 
            [ 1, 1, 0, 1, 1, 1, 0 ],  # two            3  |     |  1
            [ 1, 1, 0, 1, 0, 1, 1 ],  # three             |  4  |  
            [ 1, 0, 1, 1, 0, 0, 1 ],  # four              -------
            [ 0, 1, 1, 1, 0, 1, 1 ],  # five              |     |  
            [ 0, 1, 1, 1, 1, 1, 1 ],  # six            5  |     |  7     
            [ 1, 1, 0, 0, 0, 0, 1 ],  # seven             -------   
            [ 1, 1, 1, 1, 1, 1, 1 ],  # eight                6
            [ 1, 1, 1, 1, 0, 1, 1 ] ] # nine

aOutputs = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

weights = { 'h1': tf.Variable( tf.random_normal( [ nInputs, nHiddenPerceptrons ] ) ),
            'out': tf.Variable( tf.random_normal( [ nHiddenPerceptrons, nTypes ] ) ) }
biases = { 'b1': tf.Variable( tf.random_normal( [ nHiddenPerceptrons ] ) ),
           'out': tf.Variable( tf.random_normal( [ nTypes ] ) ) }

x = tf.placeholder( "float", shape=[ None,] )
y = tf.placeholder( "float" )

network = multilayer_perceptron( x, weights, biases )
loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits=network, labels=tf.placeholder( "float" ) ) )
optimizer = tf.train.AdamOptimizer( learning_rate = nLearningRate ).minimize( loss )
init = tf.global_variables_initializer()

with tf.Session() as session :
   session.run( init )

   # Training cycle
   for epoch in range( nTrainingEpochs ) :
      avg_loss = 0.
      for n in range( len( aInputs ) ) :
         c = session.run( [ optimizer, loss ], { x: aInputs[ n ], y: aOutputs[ n ] } )
         # Compute average loss
         avg_loss += c / total_batch
         print("Epoch:", '%04d' % ( epoch + 1 ), "cost=", "{:.9f}".format( avg_loss ) )

      print("Optimization Finished!")

但是我遇到了一些运行时错误,我不知道如何解决它们。谢谢你的帮助,谢谢


共2个答案

匿名用户

错误消息说x的形状不正确。

您需要设置形状参数的第二个维度。

x = tf.placeholder("float", shape=[None, nInputs])

匿名用户

通过这种方式解决:

# Building a neuronal network with TensorFlow

import tensorflow as tf

def multilayer_perceptron( x, weights, biases ):
    # Hidden layer with RELU activation
    layer_1 = tf.add( tf.matmul( x, weights[ 'h1' ] ), biases[ 'b1' ] )
    layer_1 = tf.nn.relu(layer_1)

    # Output layer with linear activation
    out_layer = tf.matmul( layer_1, weights[ 'out' ] ) + biases[ 'out' ] 
    return out_layer

session = tf.Session()

nInputs = 7  # Number of inputs to the neuronal network
nHiddenPerceptrons = 12
nTypes = 10  # Number of different types in the output
nLearningRate = 0.002
nTrainingEpochs = 500

# Input data
aInputs = [ [ 1, 1, 1, 0, 1, 1, 1 ],  # zero                 2
            [ 1, 0, 0, 0, 0, 0, 1 ],  # one               ------- 
            [ 1, 1, 0, 1, 1, 1, 0 ],  # two            3  |     |  1
            [ 1, 1, 0, 1, 0, 1, 1 ],  # three             |  4  |  
            [ 1, 0, 1, 1, 0, 0, 1 ],  # four              -------
            [ 0, 1, 1, 1, 0, 1, 1 ],  # five              |     |  
            [ 0, 1, 1, 1, 1, 1, 1 ],  # six            5  |     |  7     
            [ 1, 1, 0, 0, 0, 0, 1 ],  # seven             -------   
            [ 1, 1, 1, 1, 1, 1, 1 ],  # eight                6
            [ 1, 1, 1, 1, 0, 1, 1 ] ] # nine

aOutputs = [ [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],
             [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
             [ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ],
             [ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ],
             [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],
             [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ],
             [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ],
             [ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ],
             [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ],
             [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ] ]

input = tf.placeholder( "float", shape=( None, nInputs ) )
output = tf.placeholder( "float", shape=( None, nTypes ) )

# Store layers weight & bias
weights = { 'h1': tf.Variable(tf.random_normal( [ nInputs, nHiddenPerceptrons ] ) ),
            'out': tf.Variable(tf.random_normal( [ nHiddenPerceptrons, nTypes ] ) ) }
biases = { 'b1': tf.Variable( tf.random_normal( [ nHiddenPerceptrons ] ) ),
           'out': tf.Variable( tf.random_normal( [ nTypes ] ) ) }

# Create model
network = multilayer_perceptron( input, weights, biases )
loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits=network, labels=output ) )
optimizer = tf.train.AdamOptimizer( learning_rate = nLearningRate ).minimize( loss )
init = tf.global_variables_initializer()

with tf.Session() as session:
   session.run( init )

   # Training cycle
   for epoch in range( nTrainingEpochs ) :
       avg_error = 0
       for n in range( len( aInputs ) ) :
          cost = session.run( [ optimizer, loss ], { input: [ aInputs[ n ] ], output: [ aOutputs[ n ] ] } )
          # Compute average error
          avg_error += cost[ 1 ] / len( aInputs )

       print( "Epoch:", '%04d' % ( epoch + 1 ), "error=", "{:.9f}".format( avg_error ) )

   print( "Optimization Finished" )

   # Test model on train data
   print( "Testing:" )
   for n in range( len( aInputs ) ) :
      print( tf.argmax( network, 1 ).eval( { input: [ aInputs[ n ] ] } )[ 0 ] )