我正在使用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,1] ]
y = [ 0,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,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,0]
因此,要求它对零个输入进行预测,则给出4个预测。要求它根据一个输入进行预测就得出4个预测。此外,它给出的预测看起来就像我们将整个训练集放入预测函数所期望的一样。
关于发生了什么的任何想法?如何让我的网络对给定的每个输入给出准确的一个预测?