开发者社区> 问答> 正文

一个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!")

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

展开
收起
祖安文状元 2020-02-23 16:15:50 1316 0
2 条回答
写回答
取消 提交回答
  • 亲,你这也太懒了,贴个错误信息呗。

    2020-03-14 14:17:37
    赞同 展开评论 打赏
  • 误消息指出x的形状不正确。

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

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

    2020-02-23 16:15:56
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
深度学习框架实战-Tensorflow 立即下载
From Python Scikit learn to Scala Spark 立即下载