Skip to main content
 首页 » 编程设计

python之TensorFlow:对图像进行分类

2024年09月03日27mq0036

我正在学习有关使用 TensorFlow 2.0 进行图像分类的教程:https://www.tensorflow.org/tutorials/images/classification

教程展示了如何构建和训练模型,但我不明白如何实际使用该模型。

我正在寻找的是一种在图像中传递 an 的方法(最好只是它的路径)并返回某种分类结果。像这样:

result = model.evaluate('path/to/image.jpg') 
# result == {'cat': 0.92, 'dog': 0.08} 

如何实现?另外,模型保存在哪里,训练完成后如何访问?

请您参考如下方法:

对于打印出图像是 X% 猫、%Y 狗、this 的概率结果的特定情况特定的 tensorflow 教程可能更有用。

在其中,他们确实介绍了如何绘制可能性百分比,以及使用 tensorflow 的大部分基础知识。

训练模型后,您可以使用更多代码以图形方式显示结果,如本教程中的以下代码:

def plot_image(i, predictions_array, true_label, img): 
  predictions_array, true_label, img = predictions_array, true_label[i], img[i] 
  plt.grid(False) 
  plt.xticks([]) 
  plt.yticks([]) 
 
  plt.imshow(img, cmap=plt.cm.binary) 
 
  predicted_label = np.argmax(predictions_array) 
  if predicted_label == true_label: 
    color = 'blue' 
  else: 
    color = 'red' 
 
  plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 
                                100*np.max(predictions_array), 
                                class_names[true_label]), 
                                color=color) 
 
def plot_value_array(i, predictions_array, true_label): 
  predictions_array, true_label = predictions_array, true_label[i] 
  plt.grid(False) 
  plt.xticks(range(10)) 
  plt.yticks([]) 
  thisplot = plt.bar(range(10), predictions_array, color="#777777") 
  plt.ylim([0, 1]) 
  predicted_label = np.argmax(predictions_array) 
 
  thisplot[predicted_label].set_color('red') 
  thisplot[true_label].set_color('blue') 

然后,使用以下代码,您可以绘制一些关于结果的图表:

至于访问您的模型并保存它,以下 tensorflow tutorial可能会有用。

希望对您有所帮助!