Caffe:尽可能简单地预测快照中的图像

时间:2016-06-20 07:35:10

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

有没有办法轻松使用Caffe Snapshot来预测新的图像?

和“EASILY”我的意思是:

  1. 未手动更改train.prototxtdeploy.prototxt并谨慎考虑。
  2. 没有将文件转换为LMDB(或其他类似的格式),只使用简单的简单图像文件(没有任何文件名列表或东西)
  3. 仅使用python代码(并且没有CLI)
  4. 我已经根据Caffe MNIST示例训练了二进制分类网络。我改变MNIST用于分类2级,它训练非常好。但是现在我已经完成了对网络的训练并生成了快照(包含'snapshot.caffemodel'和'solver.caffemodel'),我仍然坚持如何使用这个快照来预测JUST ONE图像,而不会有任何麻烦......

    我目前的代码是(我真的更喜欢我能做的预测就像这样简单):

    #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处理事物的当前方式有时看起来过于复杂,特别是对于使用快照预测图像等琐碎任务... 也许我做错了事......

1 个答案:

答案 0 :(得分:3)

您需要手动train_val.prototxt更改为deploy.protoxt
但是,这种变化比你想象的要容易。

train_val.prototxt复制到新deploy.prototxt并根据以下步骤修改deploy.prototxt

首先改变:输入。

不是使用训练/验证数据集(通常表示为"Data" / "HDF5Data" / "Imagedata"图层),而是需要告诉caffe将内存分配给稍后您将要使用的图像手动提供 为此,您需要删除现有的输入图层(适用于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发布。