gpt4 book ai didi

python - TensorFlow 无法识别 feed_dict 输入

转载 作者:行者123 更新时间:2023-11-30 22:01:41 24 4
gpt4 key购买 nike

我正在运行一个简单的神经网络进行线性回归。然而,TensorFlow 提示我的 feed_dict 占位符不是图表的元素。然而,我的占位符和模型都在我的图表中定义,如下所示:

import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense

with tf.Graph().as_default():
x = tf.placeholder(dtype=tf.float32, shape = (None,4))
y = tf.placeholder(dtype=tf.float32, shape = (None,4))

model = tf.keras.Sequential([
Dense(units=4, activation=tf.nn.relu)
])
y = model(x)

loss = tf.reduce_mean(tf.square(y-x))
train_op = tf.train.AdamOptimizer().minimize(loss)

with tf.Session() as sess:
sess.run(train_op, feed_dict = {x:np.ones(dtype='float32', shape=(4)),
y:5*np.ones(dtype='float32', shape=(4,))})

这会产生错误:

TypeError: Cannot interpret feed_dict key as Tensor: Tensor 
Tensor("Placeholder:0", shape=(?, 4), dtype=float32) is not an element of this graph.

____________更新________________

根据@Silgon和@Mcangus的建议,我修改了代码:

g= tf.Graph()
with g.as_default():
x = tf.placeholder(dtype=tf.float32, shape = (None,4))

model = tf.keras.Sequential([
Dense(units=4, activation=tf.nn.relu)
])
y = model(x)

loss = tf.reduce_mean(tf.square(y-x))
train_op = tf.train.AdamOptimizer().minimize(loss)

init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
with tf.Session(graph=g) as sess:
sess.run(init_op)
for i in range(5):
_ , answer = sess.run([train_op,loss], feed_dict = {x:np.ones(dtype='float32', shape=(1,4)),
y:5*np.ones(dtype='float32', shape=(1,4))})
print(answer)

但是模型似乎并没有学习:

16.0
16.0
16.0
16.0
16.0

最佳答案

该错误告诉您该变量不是图形的元素。可能是因为不在同一个范围内。解决这个问题的一种方法是采用如下结构。

# define a graph
graph = tf.Graph()
with graph.as_default():
# placeholder
x = tf.placeholder(...)
y = tf.placeholder(...)
# create model
model = create_model(x, w, b)

with tf.Session(graph=graph) as sess:
# initialize all the variables
sess.run(init)

此外,正如 @Mcangus 指出的那样,请小心变量的定义。

关于python - TensorFlow 无法识别 feed_dict 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com