tensorflow——tf.placeholder用法

本文深入解析TensorFlow中tf.placeholder函数的使用方法,通过实例演示如何在计算图中使用占位符配合Session.run()、Tensor.eval()或Operation.run()进行数据输入。并展示了一个神经网络训练的例子,说明在复杂模型中如何正确使用占位符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.tensorflow.org/api_docs/python/tf/placeholder

tf.placeholder(
    dtype,
    shape=None,
    name=None
)

很简单的函数,仅有3个参数,并且只有第一个dtype是必须参数。
重要的是:这个张量在计算时会产生误差。必须使用feed_dict可选参数将其值提供给Session.run()、Tensor.eval()或Operation.run()。

说白了,只有
Session.run()
Tensor.eval()
Operation.run()
这3个函数才能有feed_dict,才能配合tf.placeholder使用

例子

import tensorflow as tf

# case1:简单点的情况
import tensorflow as tf

# case1:简单点的情况
x = tf.placeholder(tf.float32)
y = x*x

# case2:复杂点的情况
s = tf.placeholder(tf.int16)  # tf默认的整数类型其实是32
t = tf.placeholder(tf.int16)
u = t + s +tf.constant(1, dtype=tf.int16)
v= tf.placeholder(tf.int16)
w = u * v

init = tf.global_variables_initializer
with tf.Session() as sess:
  print(sess.run(y, feed_dict={x: 3.0}))
  print(sess.run(w, feed_dict={s: 1, t: 3, v: 2}))
  writer = tf.summary.FileWriter("logs", sess.graph)  # 文件写在该.py文件同级


在这里插入图片描述
总结:
要运算什么,如y,用sess.run(y)即可,如若y的构成关系中,含有tf.placeholder,则需要在sess.run(y)括号内,加入feed_dict=参数,该参数以字典形式给出构成y的各个placeholder的值。如上边例子中:
case1:y由x构成,则feed_dict中要包含x
case2:w由s,t,v构成,则feed_dict中要包含s,t,v
具体所求量包含什么,要自己去代码中查找,貌似没有一个自动的函数。

ps:图中可以看出,代码中的变量名,并不反映在graph中,想要反映在graph中的变量名,必须在api的name参数中给出。


第一次写的

在这里插入图片描述

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

#构造输入数据(我们用神经网络拟合x_data和y_data之间的关系)
x_data = np.linspace(-1,1,300)[:, np.newaxis] #-11等分300份形成的二维矩阵
noise = np.random.normal(0,0.05, x_data.shape) #噪音,形状同x_data在0-0.05符合正态分布的小数
y_data = np.square(x_data)-0.5+noise #x_data平方,减0.05,再加噪音值
plt.plot(x_data,y_data)
# plt.show()

#输入层(1个神经元)
xs = tf.placeholder(tf.float32, [None, 1]) #占位符,None表示n*1维矩阵,其中n不确定
ys = tf.placeholder(tf.float32, [None, 1]) #占位符,None表示n*1维矩阵,其中n不确定

#隐层(10个神经元)
W1 = tf.Variable(tf.random_normal([1,10])) #权重,1*10的矩阵,并用符合正态分布的随机数填充
b1 = tf.Variable(tf.zeros([1,10])+0.1) #偏置,1*10的矩阵,使用0.1填充
Wx_plus_b1 = tf.matmul(xs,W1) + b1 #矩阵xs和W1相乘,然后加上偏置 shape=[1,10]
output1 = tf.nn.relu(Wx_plus_b1) #激活函数使用tf.nn.relu

#输出层(1个神经元)
W2 = tf.Variable(tf.random_normal([10,1]))
b2 = tf.Variable(tf.zeros([1,1])+0.1)
Wx_plus_b2 = tf.matmul(output1,W2) + b2 # shape=[1, 1]
output2 = Wx_plus_b2

#损失
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-output2),reduction_indices=[1])) #在第一维上,偏差平方后求和,再求平均值,来计算损失
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 使用梯度下降法,设置步长0.1,来最小化损失

#初始化
init = tf.global_variables_initializer() #初始化所有变量
sess = tf.Session()
sess.run(init) #变量初始化

#训练
lxq=[]
for i in range(1000): #训练1000次
    _,loss_value = sess.run([train_step,loss],feed_dict={xs:x_data,ys:y_data}) #进行梯度下降运算,并计算每一步的损失
    # lxq.append(loss_value)
    # if(i%50==0):
    #     print(loss_value) # 每50步输出一次损失

y=sess.run(output2,feed_dict={xs:x_data})
print(y.shape)
for i in range(100):
    print(y[i]-y[i+1])
print(y)
plt.plot(x_data,y)
# plt.plot(lxq)
plt.show()

参考文献
https://www.cnblogs.com/tengge/p/6361005.html

``` !mkdir -p ~/.keras/datasets !cp work/mnist.npz ~/.keras/datasets/ import warnings warnings.filterwarnings("ignore") from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() print(f"训练数据形状: {train_images.shape}") print(f"训练标签长度: {len(train_labels)}") print(f"测试数据形状: {test_images.shape}") print(f"测试标签长度: {len(test_labels)}") from keras import models from keras import layers # 构建神经网络模型 network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) # 隐藏层:512个神经元,激活函数为ReLU network.add(layers.Dense(10, activation='softmax')) # 输出层:10个分类,激活函数为Softmax # 编译模型 network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # 数据预处理 train_images = train_images.reshape((60000, 28 * 28)) # 将图像展平成一维向量 train_images = train_images.astype('float32') / 255 # 归一化到[0,1] test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 # 标签编码 from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 训练模型 network.fit(train_images, train_labels, epochs=5, batch_size=128) # 测试模型性能 test_loss, test_acc = network.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)```WARNING: Logging before flag parsing goes to stderr. W0402 07:43:05.362896 140490082953024 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. W0402 07:43:05.367048 140490082953024 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:517: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. W0402 07:43:05.371049 140490082953024 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:4138: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.帮我指定出需要改哪里,要明确的位置
最新发布
04-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值