tensorflow 如何从我的模型中为上传的样本打印预测?

f2uvfpb9  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(145)

我刚刚完成的TensorFlow课程给出了以下示例,但我想修改一下,以打印分类(而不是二元)样本的预测。0(对应于“5”)、1(对应于“10”)和2(对应于“20”)。

import numpy as np
from google.colab import files
from tensorflow.keras.utils import load_img, img_to_array

uploaded = files.upload()

for fn in uploaded.keys():
 
  path = '/content/' + fn
  img = load_img(path, target_size=(200, 150))
  x = img_to_array(img)
  x /= 255
  x = np.expand_dims(x, axis=0)

  images = np.vstack([x])
  classes = model.predict(images, batch_size=10)
  print(classes[0])
  if classes[0]>0.5:
    print(fn + " is a human")
  else:
    print(fn + " is a horse")

我曾尝试将一组复杂的if函数组合在一起,结果导致了以下错误:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我的垃圾if语句看起来像这样:

if classes[0]=0:
    print(fn + " is a 5")
if classes[0]=1:
    print(fn + " is a 10")
if classes[0]=2:
    print(fn + " is a 20")

事后看来,我现在意识到这种方法是根本错误的,我想做的是打印数组中的最大数字(即最可能的类别)。
以测试为例,我收到了以下输出:

1/1 [==============================] - 0s 18ms/step
[0.97390795 0.00138458 0.02470746]

我希望有一个print语句,其功能与示例代码中列出的语句类似,但它选择最大值并打印相应的标签沿着概率。

sdnqo3pr

sdnqo3pr1#

predict返回数组的数组。
试试这个:

if classes[0][0] == max(classes[0]):
    print(fn + " is a 5.")
elif classes[0][1] == max(classes[0]):
    print(fn + " is a 10")
elif classes[0][2] == max(classes[0]):
    print(fn + " is a 20")

或者用一种更简洁的方式来解释字典:

dic = {
    0 : 5,
    1 : 10,
    2 : 20
}

print(fn + " is a", dic[classes[0].argmax()])

相关问题