咖啡执行

Caffe execution

我开始使用 caffe 进行深度学习。我有 .caffemodel 文件,其中包含我训练好的权重和特定的神经网络。我正在使用 python 界面。

我已经看到我可以通过这样做来加载我的网络和权重:

solver=caffe.get_solver('prototxtfile.prototxt')
solver.net.copy_from('weights.caffemodel')

但我不想微调我的应用程序。我只想使用这些权重。我想执行网络,对于 Imagenet 数据集中的每个图像,我想获得分类结果(而不是整个批次的准确性)。我该怎么做?

非常感谢。

尝试理解附加的 python 代码行并根据您的需要进行调整。这不是我的代码,但我写了一个类似的代码来测试我的模型。
来源是: https://www.cc.gatech.edu/~zk15/deep_learning/classify_test.py

如果您不想 fine-tune 一个 pre-trained 模型,很明显您不需要求解器。求解器用于优化模型。如果你想预测图像的 class 概率,你实际上只需要做一个正向传播。请记住,您的 deploy.prototxt 必须有一个适当的最后一层,它使用 softmax 或 sigmoid 函数(取决于架构)。您不能为此使用 train_val.prototxt 中的损失函数。

import numpy as np
import matplotlib.pyplot as plt

# Make sure that caffe is on the python path:
caffe_root = '../'  # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')

import caffe

# Set the right path to your model definition file, pretrained model weights,
# and the image you would like to classify.
MODEL_FILE = '../models/bvlc_reference_caffenet/deploy.prototxt'
PRETRAINED = '../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
IMAGE_FILE = 'images/cat.jpg'

caffe.set_mode_cpu()
net = caffe.Classifier(MODEL_FILE, PRETRAINED,
                       mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1),
                       channel_swap=(2,1,0),
                       raw_scale=255,
                       image_dims=(256, 256))
input_image = caffe.io.load_image(IMAGE_FILE)
plt.imshow(input_image)

prediction = net.predict([input_image])  # predict takes any number of images, and formats them for the Caffe net automatically
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax()
plt.show()

这是我需要通过我的网络转发图片时使用的代码:

import caffe

caffe.set_mode_cpu()             #If you are using CPU
#caffe.set_mode_gpu()            #or if you are using GPU

model_def = "path/to/deploy.prototxt"         #architecture
model_weights = "path/to/weights.caffemodel"  #weights

net = caffe.Net(model_def,      # defines the structure of the model
                model_weights,
                caffe.TEST)     # use test mode (e.g., don't perform dropout)


#Let's forward a single image (let's say inputImg)
#'data' is the name of my input blob
net.blobs["data"].data[0] = inputImg
out = net.forward()

# to get the final softmax probability
# in my case, 'prob' is the name of our last blob
# a softmax layer that will output the score/probability for our problem
outputScore = net.blobs["prob"].data[0]   #[0] here because we forwarded a single image

在此示例中,inputImg 尺寸必须与训练期间使用的图像尺寸以及已完成的所有预处理相匹配。