如何修复关于 TensorFlow 预测的 TypeError? [英] How to fix TypeError with respect to TensorFlow prediction?
问题描述
我一直在尝试使用 TensorFlow 执行神经网络预测,评估工作正常,但是当我将相同的数据放入预测时,它会出现类型错误.
I've been trying to perform neural network predictions with TensorFlow and the evaluation works fine but when I put the same data into prediction it gives a type error.
training_data 和 test_data 中的数据都是 2d numpy 整数数组,training_labels 和 test_labels 中的数据是 1d numpy 整数数组.
The data in training_data and test_data are both 2d numpy arrays of integers and training_labels and test_labels are 1d numpy arrays of integers.
model = keras.Sequential([
keras.layers.Dense(24, activation=tf.nn.selu),
keras.layers.Dense(10, activation=tf.nn.tanh),
keras.layers.Dense(5, activation=tf.nn.selu),
keras.layers.Dense(5, activation=tf.nn.softmax)
])
model.compile(optimizer='SGD',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_data, training_labels, epochs=10)
test_loss,test_acc = model.evaluate(test_data, test_labels)
prediction = model.predict(test_data)
当取出预测线时,代码按预期工作,但现在给出以下错误消息:
When taking out the prediction line the code works as expected but it now gives the following error message:
Traceback (most recent call last):
File "learner.py", line 132, in <module>
print("Prediction: " + model.predict(test_data))
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')
我已经确保所有数据都是整数,所以我不确定为什么会出现类型冲突.
I've made sure that all the data is integers so I'm not sure why there's type conflict.
推荐答案
test_data 使用 predict 时应与 type(training_data[0]) 的数据类型相同,并且返回类型为(training_labels[0])的数据类型
test_data should be the same datatype as type(training_data[0]) when using predict, and it will return a datatype of type(training_labels[0])
此外,
print("Prediction: " + model.predict(test_data))
必须
print("Prediction: " + str(model.predict(test_data)))
这篇关于如何修复关于 TensorFlow 预测的 TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!