函数tf.placeholder()

  • 函数形式

    tf.placeholder(
        dtype,
        shape=None,
        name=None
    )
    
  • 参数

    • dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
    • shape:数据形状。默认是None,就是一维值,也可以是多维(比如[2,3] 两行3列, [None, 3]表示列是3,行不定)
    • name:名称(可定义可不定义)
  • 使用原因:

    • Tensorflow的设计理念称之为计算流图,在编写程序时,首先构筑整个系统的graph,代码并不会直接生效,这一点和python的其他数值计算库(如Numpy等)不同,graph为静态的,类似于docker中的镜像。然后,在实际的运行时,启动一个session,程序才会真正的运行。所以placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符喂入数据。
  • 代码示例(直接附上利用TensorFlow实现非线性回归代码):

    import tensorflow as tf
    import numpy as np
    import matplotlib.pyplot as plt
    
    # s生成200个随机点
    x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
    noise = np.random.normal(0,0.02,x_data.shape)
    y_data = np.square(x_data) + noise
    
    x = tf.placeholder(tf.float32,[None,1])
    y = tf.placeholder(tf.float32,[None,1])
    
    # 定义神经网络中间层
    Weight_L1 = tf.Variable(tf.random_normal([1,10]))
    biases_L1 = tf.Variable(tf.random_normal([1,10]))
    Wx_plus_b_L1 = tf.matmul(x,Weight_L1) + biases_L1
    L1 = tf.nn.tanh(Wx_plus_b_L1)
    
    # 定义神经网络输出层
    Weight_L2 = tf.Variable(tf.random_normal([10,1]))
    biases_L2 = tf.Variable(tf.zeros([1,1]))
    Wx_plus_b_L2 = tf.matmul(L1,Weight_L2) + biases_L2
    prediction = tf.nn.tanh(Wx_plus_b_L2)
    
    # 二次代价函数
    loss = tf.reduce_mean(tf.square(y-prediction))
    # 使用梯度下降法训练
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for _ in range(2000):
            sess.run(train_step,feed_dict={
          
          x:x_data, y:y_data})
            
        prediction_value = sess.run(prediction, feed_dict={
          
          x:x_data})
        
        plt.figure()
        plt.scatter(x_data,y_data)
        
        plt.plot(x_data,prediction_value,'r-',lw=5)
        plt.show()
    

猜你喜欢

转载自blog.csdn.net/qq_42546127/article/details/114670679