【发布时间】:2019-11-12 19:08:49
【问题描述】:
我使用的是 Ubuntu 19.04 (Disco Dingo)、Python 3.7.3 和 TensorFlow 1.14.0。
我注意到 tensorflow.keras.Sequential.predict 函数给出的输出数量与输入数量不同。此外,输入和输出之间似乎没有关系。
例子:
import tensorflow as tf
import math
import numpy as np
import json
# We will train the model to recognize an XOR
x = [ [0,0], [0,1], [1,0], [1,1] ]
y = [ 0, 1, 1, 0 ]
xt = tf.cast(x, tf.float64)
yt = tf.cast(y, tf.float64)
# This model should be more than enough to learn an XOR
L0 = tf.keras.layers.Dense(2)
L1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
L2 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
L3 = tf.keras.layers.Dense(2, activation=tf.nn.softmax)
model = tf.keras.Sequential([L0,L1,L2,L3])
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
model.fit(
x=xt,
y=yt,
batch_size=32,
epochs=1000, # Try to overfit data
shuffle=False,
steps_per_epoch=math.ceil(len(x)/32)
)
# While it is training, the loss drops to near zero
# and the accuracy goes to 100%.
# The large number of epochs and the small number of training examples
# should mean that the network is overtrained.
print("testing")
for i in range(len(y)):
m = tf.cast([x[i]],tf.float64)
# m should be the ith training example
values = model.predict(m,steps=1)
best = np.argmax(values[0])
print(x[i],y[i],best)
我总是得到的输出是:
(输入、正确答案、预测答案)
[0, 0] 0 0
[0, 1] 1 0
[1, 0] 1 0
[1, 1] 0 0
或
[0, 0] 0 1
[0, 1] 1 1
[1, 0] 1 1
[1, 1] 0 1
所以,即使我认为网络会被过度训练,即使程序说准确率是 100% 并且损失几乎为零,但输出看起来好像网络根本没有训练过。
更奇怪的是,我将测试部分替换为以下内容:
print("testing")
m = tf.cast([], tf.float64)
values = model.predict(m, steps=1)
print(values)
我认为这将返回一个空数组或引发异常。相反,它给出了:
[[0.9979249 0.00207507]
[0.10981816 0.89018184]
[0.10981816 0.89018184]
[0.9932179 0.0067821 ]]
这对应于[0,1,1,0]
因此,即使它没有任何可预测的内容,它仍然会给出某些东西的预测。而且看起来预测与我们将整个训练集发送到预测方法所期望的结果相匹配。
再次更换测试部分:
print("testing")
m = tf.cast([[0,0]], tf.float64)
# [0,0] is the first training example
# the output should be something close to [[1.0,0.0]]
values = model.predict(m, steps=1)
for j in range(len(values)):
print(values[j])
exit()
我明白了:
[0.9112452 0.08875483]
[0.00552484 0.9944752 ]
[0.00555605 0.99444395]
[0.9112452 0.08875483]
这对应于[0,1,1,0]
因此要求它对零输入进行预测,给出 4 个预测。要求它预测一个输入会给出 4 个预测。此外,如果我们将整个训练集放入预测函数中,它给出的预测看起来就像我们所期望的那样。
关于发生了什么的任何想法?如何让我的网络对给定的每个输入都给出一个准确的预测?
【问题讨论】:
-
您的代码在 Tensorflow 2 上工作。您可以尝试将输出放入列表中,例如,
[[0],[1],[1],[0]]? -
您能说得更具体些吗?我很好奇将 [[0,0]] 传递给预测函数时会得到什么。那么空输入 tf.cast([],tf.float64) 呢?
-
当我尝试使用
[[0,0]]时,我只得到[0.9038475 0.09615252]。使用tf.cast([],tf.float64),我得到一个错误(Tensor或NumPy输入数据需要ValueError:batch_size` 或steps。, even if thesteps` 参数在那里)。请注意,我使用的是 tensorflow 2,这两个版本之间可能会有一些行为变化。 -
感谢您的帮助。从我似乎无法在互联网上找到任何关于此的事实以及您无法复制它的事实来看,我怀疑它可能是一个错误。我会尝试让 TensorFlow 2 运行,看看是否有区别。
-
使用 TensorFlow 2,该错误不存在。对于将来阅读本文的人,请确保您使用的是 Tensorflow 2。
标签: python tensorflow machine-learning keras