【问题标题】:Caffe: Predict an image from snapshot as simple as possibleCaffe:尽可能简单地从快照中预测图像
【发布时间】:2016-06-20 07:35:10
【问题描述】:

有什么方法可以轻松使用 Caffe 快照来预测新图像?

“轻松”是指:

  1. 请勿手动将train.prototxt 更改为deploy.prototxt 并谨慎考虑。
  2. 不将文件转换为 LMDB(或其他类似格式),只使用简单的图像文件(没有任何文件名列表或其他内容)
  3. 仅使用 python 代码(不使用 CLI)

我已经根据 Caffe MNIST 示例训练了一个二元分类网络。我将 MNIST 更改为用于对 2 个类别进行分类,它的训练效果非常好。但是现在我已经完成了网络的训练并生成了快照(包含'snapshot.caffemodel'和'solver.caffemodel'),我被困在如何使用这个快照来预测一个图像而没有所有的麻烦......

我当前的代码是(如果我能像这样简单地进行预测,我真的更喜欢):

#I'M NOT SURE IF I SHOULD USE 'caffe.Net(...)' OR 'caffe.Classifier(...)'
net = caffe.Classifier('Data/train.prototxt',
                       'Data/Snapshot_iter_1000.caffemodel',
                       mean=convertBinaryProtoToNPY('Data/mean_image.binaryproto'),
                       image_dims=(100, 100),
                       raw_scale=255)

score = net.predict([caffe.io.load_image('/Data/Images/1.jpg')])
print score

我收到了这个错误:

File "C:\Anaconda2\lib\site-packages\caffe\classifier.py", line 29, in __init__ in_ = self.inputs[0]
IndexError: list index out of range

搜索后我发现我不应该使用“train.prototxt”,而是使用名为“deploy.prototxt”的东西。

当前 Caffe 处理事情的方式有时似乎过于复杂,尤其是对于诸如使用快照预测图像之类的琐碎任务... 也许我做事的方式不对……

【问题讨论】:

    标签: python neural-network deep-learning caffe conv-neural-network


    【解决方案1】:

    您确实需要手动将您的 train_val.prototxt 更改为 deploy.protoxt
    然而,这种改变比你想象的要容易。

    train_val.prototxt复制到一个新的deploy.prototxt并按照以下步骤编辑deploy.prototxt

    第一个变化:输入。

    您需要告诉 caffe 为稍后手动提供的图像分配内存,而不是使用训练/验证数据集(通常表示为 "Data"/"HDF5Data"/"Imagedata" 层)。
    为此,您需要删除现有的输入层(对于 TRAIN 和 TEST 阶段),并将它们替换为:

    layer {
      name: "input"
      type: "Input"
      top: "data"  # or whatever was the name of the "top" of the training input. no need for "label" top - you do not have ground truth labels in test.
      input_param { shape: { dim: 1 dim: 3 dim: 100 dim: 100 } } # give caffe the expected dimensions of your input for memory allocation
    }
    

    第二个变化:网络的输出。

    在训练期间,您的净输出是损失,而不是预测。
    因此,首先删除 所有 损失层(特别是任何期望将"label" 作为“底部”的层)。这包括"SoftmaxWithLoss"/"Accuracy"/"SigmoidCrossEntropyLoss"等。
    您需要用适当的预测层替换损失层。例如,"SoftmaxWithLoss" 层应替换为简单的"Softmax" 层,"SigmoidCrossEntropy" 层应替换为"Sigmoid" 层等等。
    因此,如果你有类似的东西

    layer {
      type: "SoftmaxWithLoss"
      name: "loss"
      bottom: "fc8"  # we need this name !
      bottom: "label"
      ...
    }
    

    替换为:

    layer {
      name: "prob"
      type: "Softmax"
      bottom: "fc8" # the SAME as the train loss layer!
      top: "prob"
    }
    

    保存更改,现在您有一个正确的deploy.prototxt

    有关更多信息,请参阅this 帖子。

    【讨论】:

    • 感谢您的回答...我还没有尝试过,但我最终会尝试并会发布这里发生的事情...手指交叉...
    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 2012-06-06
    • 2012-08-10
    • 2015-07-12
    • 2023-03-03
    • 2019-02-21
    • 1970-01-01
    • 2016-07-30
    相关资源
    最近更新 更多