如何解决张量流问题从头开始编写简单的MLP
我正在学习tensorflow,我试图从零开始在tensorflow中实现MLP,并在MNIST数据集上对其进行测试。这是我的代码:
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.keras.losses import categorical_crossentropy
tf.disable_v2_behavior()
image_tensor = tf.placeholder(tf.float32,shape=(None,784))
label_tensor = tf.placeholder(tf.float32,10))
# Model architecture
# --> Layer 1
w1 = tf.Variable(tf.random_uniform([784,128])) # weights
b1 = tf.Variable(tf.zeros([128])) # bias
a1 = tf.matmul(image_tensor,w1) + b1
h1 = tf.nn.relu(a1)
# --> Layer 2
w2 = tf.Variable(tf.random_uniform([128,128]))
b2 = tf.zeros([128])
a2 = tf.matmul(h1,w2) + b2
h2 = tf.nn.relu(a2)
# --> output layer
w3 = tf.Variable(tf.random_uniform([128,10]))
b3 = tf.zeros([10])
a3 = tf.matmul(h2,w3) + b3
predicted_tensor = tf.nn.softmax(a3)
loss = tf.reduce_mean(categorical_crossentropy(label_tensor,predicted_tensor))
opt = tf.train.GradientDescentOptimizer(0.01)
training_step = opt.minimize(loss)
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
epochs = 50
batch = 100
iterations = len(training_images) // batch
for j in range(epochs):
start = 0
end = batch
for i in range(iterations):
image_batch = np.array(training_images[start : end])
label_batch = np.array(training_labels[start : end])
start = batch + 1
end = start + batch
_,loss = sess.run(training_step,feed_dict = {
image_tensor : image_batch,label_tensor : label_batch
})
但是当我尝试运行此代码时,出现以下错误消息:
File "MNIST3.py",line 97,in <module>
main()
File "MNIST3.py",line 88,in main
label_tensor : label_batch
TypeError: 'NoneType' object is not iterable
虽然我尝试从label_batch打印前10个样本:
print(training_labels[0 : 10])
这将是输出:
[[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
[1 0 0 0 0 0 0 0 0 0]]
当我尝试打印数据集的形状时:
print(training_images.shape)
print(training_labels.shape)
这是输出:
(10000,784)
(10000,10)
我在这里想念什么?
解决方法
您误解了错误消息(Python可能会对此造成误导,我们所有人都比这样承认的错误多卡了多次……)。即使它在您的错误中显示了label_tensor : label_batch
行,它实际上是在讨论整个session.run()
调用。
之所以出现此错误,是因为您期望该调用返回一个元组,但您仅提供一个由TensorFlow计算的张量。
sess.run(training_step,feed_dict=...)
将返回None
,因为操作training_step
不应返回任何内容,称它只是执行一个优化步骤。
要获得所需的结果,请将代码更改为:
_,loss_result = sess.run([training_step,loss],feed_dict={
image_tensor : image_batch,label_tensor : label_batch
})
这样TensorFlow将评估这2个操作,第一个将返回None(因为您已经获取了),第二个将计算给定批次的损失函数的值。
(请注意,您必须在左侧重命名loss变量,因为如果不这样做,您将替换loss op,下一次调用可能会引发异常或更糟的情况,只是给出错误的结果)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。