如何针对TensorFlow预测修复TypeError?

时间:2019-05-30 15:36:44

标签: python tensorflow

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

training_data和test_data中的数据都是二维的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')

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

1 个答案:

答案 0 :(得分:0)

使用预测时,test_data的数据类型应与type(training_data [0])相同,并且它将返回type(training_labels [0])的数据类型

此外,

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

必须

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