首页 > 解决方案 > 如何修复关于 TensorFlow 预测的 TypeError?

问题描述

我一直在尝试使用 TensorFlow 执行神经网络预测,并且评估工作正常,但是当我将相同的数据放入预测时,它会给出类型错误。

training_data 和 test_data 中的数据都是 2d numpy 整数数组,training_labels 和 test_labels 是 1d numpy 整数数组。

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)

取出预测线时,代码按预期工作,但现在给出以下错误消息:

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')

我已经确保所有数据都是整数,所以我不确定为什么会出现类型冲突。

标签: pythontensorflow

解决方案


使用 predict 时 test_data 应与 type(training_data[0]) 的数据类型相同,它会返回 type(training_labels[0]) 的数据类型

此外,

print("Prediction: " + model.predict(test_data))

一定是

print("Prediction: " + str(model.predict(test_data)))

推荐阅读