TensorFlow简单示例

时间:2017-08-10 23:28:07

标签: 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!")

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

  

文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ common_shapes.py",第671行,_call_cpp_shape_fn_impl       input_tensors_as_shapes,status)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ contextlib.py",第88行,退出       下一个(self.gen)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ errors_impl.py",第466行,在raise_exception_on_not_ok_status中       pywrap_tensorflow.TF_GetCode(状态))   tensorflow.python.framework.errors_impl.InvalidArgumentError:Shape必须是等级2,但对于' MatMul'是等级1。 (op:' MatMul')输入形状:[?],[7,5]。   在处理上述异常期间,发生了另一个异常:   Traceback(最近一次调用最后一次):     文件" tf_nn.py",第42行,in       network = multilayer_perceptron(x,权重,偏见)     在polym_perceptron中的文件" tf_nn.py",第7行       layer_1 = tf.add(tf.matmul(x,权重[' h1']),偏见[' b1'])     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ ops \ math_ops.py",第1816行,在matmul中       a,b,transpose_a = transpose_a,transpose_b = transpose_b,name = name)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ ops \ gen_math_ops.py",第1217行,在_mat_mul中       transpose_b = transpose_b,name = name)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ op_def_library.py",第767行,在apply_op中       op_def = op_def)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ ops.py",第2508行,在create_op中       set_shapes_for_outputs(RET)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ ops.py",第1873行,在set_shapes_for_outputs中       shapes = shape_func(op)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ ops.py",第1823行,在call_with_requiring中       return call_cpp_shape_fn(op,require_shape_fn = True)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ common_shapes.py",第610行,在call_cpp_shape_fn中       debug_python_shape_fn,require_shape_fn)     文件" C:\ Users \ Administrator \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ tensorflow \ python \ framework \ common_shapes.py",第676行,_call_cpp_shape_fn_impl       提出ValueError(err.message)   ValueError:Shape必须是等级2,但对于' MatMul'是等级1 (op:' MatMul')输入形状:[?],[7,5]。

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

解决这个问题:

# 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 ] )