首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >一个TensorFlow简单示例

一个TensorFlow简单示例
EN

Stack Overflow用户
提问于 2017-08-10 23:28:06
回答 2查看 1K关注 0票数 0

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

代码语言:javascript
运行
复制
# 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中,状态)文件"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\contextlib.py",行88,在"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\errors_impl.py",exit next(self.gen) File 第466行中,在raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(Status)中,tensorflow.python.framework.errors_impl.InvalidArgumentError:形状必须为2级,但对于输入形状为:,则为“MatMul”(op:'MatMul')的级别1。7,5.在处理上述异常期间,发生了另一个异常:跟踪(最近一次调用):文件"tf_nn.py",第42行,在网络= multilayer_perceptron( x,权重,偏差)文件“tf_nn.py”中,第7行,在multilayer_perceptron layer_1 = tf.add(tf.matmul(x,权重‘h1’)中,文件"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中,文件"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行,在"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py",create_op set_shapes_for_outputs(ret)文件第1873行中,在set_shapes_for_outputs File = shape_func(op)文件"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py",第1823行中,在"C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\common_shapes.py",call_with_requiring返回call_cpp_shape_fn(op,require_shape_fn=True)文件行610中,在call_cpp_shape_fn debug_python_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 raise (err.message) ValueError: Shape中必须为2级,但对于“MatMul”(op:'MatMul'),输入形状为:,7,5。

EN

回答 2

Stack Overflow用户

发布于 2017-08-11 13:19:25

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

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

代码语言:javascript
运行
复制
x = tf.placeholder("float", shape=[None, nInputs])
票数 0
EN

Stack Overflow用户

发布于 2017-08-15 01:06:29

以这种方式解决:

代码语言:javascript
运行
复制
# 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 ] )
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45624841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档