Skip to main content
 首页 » 编程设计

python之TensorFlow:在自定义图像数据集上训练模型

2024年10月01日26Terrylee

我有兴趣在我自己的图像集上训练和评估卷积神经网络模型。我想将 tf.layers 模块用于我的模型定义,并使用 tf.learn.Estimator 对象来使用 fit( ) 和 evaluate() 方法。

Here是我一直关注的教程,它有助于展示 tf.layers 模块和 tf.learn.Estimator 类。但是,它使用的数据集 (MNIST) 只是简单地导入和加载(作为 NumPy 数组)。请参阅教程脚本中的以下主要功能:

def main(unused_argv): 
  # Load training and eval data 
  mnist = learn.datasets.load_dataset("mnist") 
  train_data = mnist.train.images  # Returns np.array 
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32) 
  eval_data = mnist.test.images  # Returns np.array 
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) 
 
  # Create the Estimator 
  mnist_classifier = learn.Estimator( 
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model") 
 
  # Set up logging for predictions 
  # Log the values in the "Softmax" tensor with label "probabilities" 
  tensors_to_log = {"probabilities": "softmax_tensor"} 
  logging_hook = tf.train.LoggingTensorHook( 
      tensors=tensors_to_log, every_n_iter=50) 
 
  # Train the model 
  mnist_classifier.fit( 
      x=train_data, 
      y=train_labels, 
      batch_size=100, 
      steps=20000, 
      monitors=[logging_hook]) 
 
  # Configure the accuracy metric for evaluation 
  metrics = { 
      "accuracy": 
          learn.MetricSpec( 
              metric_fn=tf.metrics.accuracy, prediction_key="classes"), 
  } 
 
  # Evaluate the model and print results 
  eval_results = mnist_classifier.evaluate( 
      x=eval_data, y=eval_labels, metrics=metrics) 
  print(eval_results) 

完整代码 here


我有我自己的图片,在特定的目录结构中我有两种 jpg 格式:

data 
    train 
        classA 
            1.jpg 
            2.jpg 
            ... 
        classB 
            3.jpg 
            4.jpg 
            ... 
        ... 
    validate 
        classA 
            5.jpg 
            6.jpg 
            ... 
        classB 
            ... 
        ... 

我还将我的图像目录转换为 TFRecord 格式,其中一个 TFRecord 文件用于 train,一个用于 validation。我关注了this教程,它使用 build_image_data.py来自 TensorFlow 附带的 Inception 模型的脚本作为输出这些 TFRecord 文件的黑盒。我承认我创建这些可能有点本末倒置,但我认为也许有一种方法可以将它们用作 tf.learn.Estimator 的 的输入>fit() 和 evaluate() 方法。


问题

如何格式化我的 jpg(或 TFRecord)数据,以便我可以将它们用作 Estimator 对象函数的输入?

我假设我必须将我的图像和标签转换为 NumPy 数组,如上面的代码所示,但是,尚不清楚 mnist.train.images 和 mnist.train.validation 被格式化。

有没有人有将 jpg 文件和标签转换为此 Estimator 类期望作为输入的 NumPy 数组的经验?

如有任何帮助,我们将不胜感激。

请您参考如下方法:

您引用的文件 cnn_mnist.py,特别是以下函数 mnist_classifier.fit,需要 Numpy 数组作为 x 的输入> 和 y。因此,我将解决您的第二个和第三个问题,因为可能不容易将 TFRecords 合并到引用的代码中。

however, it is not clear how the mnist.train.images and mnist.train.validation are formatted

mnist.train.images 是一个形状为 (55000, 784) 的 Numpy 数组,其中 55000 是图像的数量,784 是每个展平图像的尺寸 (28 x 28)。 mnist.validation.images 也是一个形状为 (5000, 784) 的 Numpy 数组。

Does anyone have any experience with converting jpg files and labels to NumPy arrays that this Estimator class expects as inputs?

以下代码将一张 JPEG 图像作为三维 Numpy 数组读入:

    from scipy.misc import imread 
    filename = '1.jpg' 
    np_1 = imread(filename) 

我假设所有这些图像的大小都相同,或者您可以将它们调整为相同的大小,考虑到您已经从该数据集生成了 TFRecords 文件。剩下要做的就是展平图像,迭代读取其他图像并展平它们,然后垂直堆叠所有图像。该对象可以输入到 Estimator 函数中。

下面是展平和垂直堆叠两个三维 Numpy 数组的代码:

    import numpy as np 
    np_1_2 = np.vstack((np_1.flatten(), np_2.flatten()))