python - 如何修复关于 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')
我已经确保所有数据都是整数,所以我不确定为什么会出现类型冲突。
解决方案
使用 predict 时 test_data 应与 type(training_data[0]) 的数据类型相同,它会返回 type(training_labels[0]) 的数据类型
此外,
print("Prediction: " + model.predict(test_data))
一定是
print("Prediction: " + str(model.predict(test_data)))
推荐阅读
- pdf - Itext7 清理方法抛出错误 - 索引超出范围
- android - UPI 付款在 razorpay Android 集成中不起作用
- javascript - Node.js - 服务器端命令提示符命令输入?
- asp.net-core-webapi - dotnet ef dbcontext 脚手架在 vs2019 中无法正常工作
- ruby - 使用 fastlane 时在任何源中都找不到 rake-12.3.3
- python - Python Plotly Sankey 图:链接通过节点而不是围绕它们
- java - 如何避免重新部署相同的工件?
- python - 如何防止crontab同时执行?
- java - Scala IntList 到 Java
- string - 如何找到包含给定字符串的双端 fastq 文件的百分比