Python caffe.TEST Example(Demo)
下面提供了caffe python的六个测试demo,大家可以根据自己的需求进行修改。
Example 1
- From project FaceDetection_CNN-master, under directory , in source file test.py.
def convert_full_conv():
# Load the original network and extract the fully connected layers' parameters.
net = caffe.Net('deploy.prototxt',
'alexNet__iter_60000.caffemodel',
caffe.TEST)
params = ['fc6', 'fc7', 'fc8_flickr']
fc_params = {pr: (net.params[pr][0].data, net.params[pr][1].data) for pr in params}
# Load the fully convolutional network to transplant the parameters.
net_full_conv = caffe.Net('face_full_conv.prototxt',
'alexNet__iter_60000.caffemodel',
caffe.TEST)
params_full_conv = ['fc6-conv', 'fc7-conv', 'fc8-conv']
conv_params = {pr: (net_full_conv.params[pr][0].data, net_full_conv.params[pr][1].data) for pr in params_full_conv}
for pr, pr_conv in zip(params, params_full_conv):
conv_params[pr_conv][0].flat = fc_params[pr][0].flat # flat unrolls the arrays
conv_params[pr_conv][1][...] = fc_params[pr][1]
net_full_conv.save('face_full_conv.caffemodel')
Example 2
- From project visual-concepts-master, under directory , in source file test_model.py.
def load_model(prototxt_file, model_file, base_image_size, mean, vocab):
"""
Load the model from file. Includes pointers to the prototxt file,
caffemodel file name, and other settings - image mean, base_image_size, vocab
"""
model = {};
model['net']= caffe.Net(prototxt_file, model_file, caffe.TEST);
model['base_image_size'] = base_image_size;
model['means'] = mean; model['vocab'] = vocab;
return model
Example 3
- From project SketchingAI-master, under directory src, in source file gendraw.py.
- Caffe中只给出了分类模型classify.py,如果想写预测模型predict.py可以参考这个
def test_old():
with open(labelspath,"r") as opened_file:
labels = opened_file.readlines()
caffe.set_mode_gpu()
net = caffe.Net(model_file, pretrained, caffe.TEST)
transformer = caffe.io.Transformer({"data": net.blobs["data"].data.shape})
transformer.set_transpose("data",(2,0,1))
transformer.set_mean("data",numpy.load(caffe_root+"/python/caffe/imagenet/ilsvrc_2012_mean.npy").mean(1).mean(1))
transformer.set_raw_scale("data",255)
transformer.set_channel_swap("data",(2,1,0))
net.blobs["data"].reshape(1,3,227,227)
test_image = dataroot+"/homecat.jpg"
test_image1 = dataroot+"/241.png"
net.blobs["data"].data[...] = transformer.preprocess("data", caffe.io.load_image(test_image1))
out = net.forward()
print net.blobs["fc6"].data.shape
prediction = out["prob"]
indices = numpy.argpartition(prediction[0],-10)[-10:]
print prediction[0].argmax(), labels[prediction[0].argmax()]
net.blobs["data"].data[...] = transformer.preprocess("data", caffe.io.load_image(test_image))
out = net.forward()
print net.blobs["fc6"].data.shape
prediction = out["prob"]
indices = numpy.argpartition(prediction[0],-10)[-10:]
print prediction[0].argmax(), labels[prediction[0].argmax()]
for index in indices:
print labels[index]
Example 4
- From project fast-rcnn-master, under directory tools, in source file compress_net.py.
def main():
args = parse_args()
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
net_svd = caffe.Net(args.prototxt_svd, args.caffemodel, caffe.TEST)
print('Uncompressed network {} : {}'.format(args.prototxt, args.caffemodel))
print('Compressed network prototxt {}'.format(args.prototxt_svd))
out = os.path.splitext(os.path.basename(args.caffemodel))[0] + '_svd'
out_dir = os.path.dirname(args.caffemodel)
# Compress fc6
if net_svd.params.has_key('fc6_L'):
l_fc6 = net_svd.params['fc6_L'][0].data.shape[0]
print(' fc6_L bottleneck size: {}'.format(l_fc6))
# uncompressed weights and biases
W_fc6 = net.params['fc6'][0].data
B_fc6 = net.params['fc6'][1].data
print(' compressing fc6...')
Ul_fc6, L_fc6 = compress_weights(W_fc6, l_fc6)
assert(len(net_svd.params['fc6_L']) == 1)
# install compressed matrix factors (and original biases)
net_svd.params['fc6_L'][0].data[...] = L_fc6
net_svd.params['fc6_U'][0].data[...] = Ul_fc6
net_svd.params['fc6_U'][1].data[...] = B_fc6
out += '_fc6_{}'.format(l_fc6)
# Compress fc7
if net_svd.params.has_key('fc7_L'):
l_fc7 = net_svd.params['fc7_L'][0].data.shape[0]
print ' fc7_L bottleneck size: {}'.format(l_fc7)
W_fc7 = net.params['fc7'][0].data
B_fc7 = net.params['fc7'][1].data
print(' compressing fc7...')
Ul_fc7, L_fc7 = compress_weights(W_fc7, l_fc7)
assert(len(net_svd.params['fc7_L']) == 1)
net_svd.params['fc7_L'][0].data[...] = L_fc7
net_svd.params['fc7_U'][0].data[...] = Ul_fc7
net_svd.params['fc7_U'][1].data[...] = B_fc7
out += '_fc7_{}'.format(l_fc7)
filename = '{}/{}.caffemodel'.format(out_dir, out)
net_svd.save(filename)
print 'Wrote svd model to: {:s}'.format(filename)
Example 5
- From project DIGITS-master, under directory digits/model/tasks, in source file caffe_train.py.
def get_net(self, epoch=None):
"""
Returns an instance of caffe.Net
Keyword Arguments:
epoch -- which snapshot to load (default is -1 to load the most recently generated snapshot)
"""
if not self.has_model():
return False
file_to_load = None
if not epoch:
epoch = self.snapshots[-1][1]
file_to_load = self.snapshots[-1][0]
else:
for snapshot_file, snapshot_epoch in self.snapshots:
if snapshot_epoch == epoch:
file_to_load = snapshot_file
break
if file_to_load is None:
raise Exception('snapshot not found for epoch "%s"' % epoch)
# check if already loaded
if self.loaded_snapshot_file and self.loaded_snapshot_file == file_to_load \
and hasattr(self, '_caffe_net') and self._caffe_net is not None:
return self._caffe_net
if config_value('caffe_root')['cuda_enabled'] and\
config_value('gpu_list'):
caffe.set_mode_gpu()
# load a new model
self._caffe_net = caffe.Net(
self.path(self.deploy_file),
file_to_load,
caffe.TEST)
self.loaded_snapshot_epoch = epoch
self.loaded_snapshot_file = file_to_load
return self._caffe_net
Example 6
- From project DIGITS-master, under directory examples/classification, in source file example.py.
def get_net(caffemodel, deploy_file, use_gpu=True):
"""
Returns an instance of caffe.Net
Arguments:
caffemodel -- path to a .caffemodel file
deploy_file -- path to a .prototxt file
Keyword arguments:
use_gpu -- if True, use the GPU for inference
"""
if use_gpu:
caffe.set_mode_gpu()
# load a new model
return caffe.Net(deploy_file, caffemodel, caffe.TEST)
Python caffe.TEST Example(Demo)的更多相关文章
- appium+Python真机运行测试demo的方法
appium+Python真机运行测试demo的方法 一, 打开手机的USB调试模式 二, 连接手机到电脑 将手机用数据线连接到电脑,并授权USB调试模式.查看连接的效果,在cmd下运行命 ...
- make pycaffe时候报错:Makefile:501: recipe for target 'python/caffe/_caffe.so' failed
安装caffe-ssd编译环境的时候报错: python/caffe/_caffe.cpp:10:31: fatal error: numpy/arrayobject.h: No such file ...
- Chapter 3 Start Caffe with MNIST Demo
先从一个具体的例子来开始Caffe,以MNIST手写数据为例. 1.下载数据 下载mnist到caffe-master\data\mnist文件夹. THE MNIST DATABASE:Yann L ...
- 第一个 Python 程序 - Email Manager Demo
看了一些基础的 Python 新手教程后,深深感觉到 Python 的简洁与强大,这是我的第一个 Python Demo.下面是完整代码与执行截图. 代码: # encoding: utf-8 ''' ...
- 安装python caffe过程中遇到的一些问题以及对应的解决方案
关于系统环境: Ubuntu 16.04 LTS cuda 8.0 cudnn 6.5 Anaconda3 编译pycaffe之前需要配置文件Makefile.config ## Refer to h ...
- python 词云小demo
词云小demo jiebawordcloud 一 什么是词云? 由词汇组成类似云的彩色图形.“词云”就是对网络文本中出现频率较高的“关键词”予以视觉上的突出,形成“关键词云层”或“关键词渲染”,从而过 ...
- Python实例---简单购物车Demo
简单购物车Demo # version: python3.2.5 # author: 'FTL1012' # time: 2017/12/7 09:16 product_list = ( ['Java ...
- python caffe 在师兄的代码上修改成自己风格的代码
首先,感谢师兄的帮助.师兄的代码封装成类,流畅精美,容易调试.我的代码是堆积成的,被师兄嘲笑说写脚本.好吧!我的代码只有我懂,哈哈! 希望以后代码能写得工整点.现在还是让我先懂.这里,我做了一个简单的 ...
- python+caffe训练自己的图片数据流程
1. 准备自己的图片数据 选用部分的Caltech数据库作为训练和测试样本.Caltech是加州理工学院的图像数据库,包含Caltech101和Caltech256两个数据集.该数据集是由Fei-Fe ...
随机推荐
- http协议详解(1)
HTTP协议报文格式 接下来我们看看HTTP协议(Hypertext Transfer Protocol――超文本传输协议)浏览器端(客户端)向WEB服务器端访问页面的过程和HTTP协议报文的格式. ...
- .Net framework 的浏览器定义文件
.net framework4.5.1之前的版本有一个非常愚蠢的设定, 它为每个浏览器设置了一个浏览器定义文件, 通过正则表达式来匹配浏览器的userAgent, 然后来定义一些功能集. 这种做法有一 ...
- Codeforces Round #361 (Div. 2) E. Mike and Geometry Problem
题目链接:传送门 题目大意:给你n个区间,求任意k个区间交所包含点的数目之和. 题目思路:将n个区间都离散化掉,然后对于一个覆盖的区间,如果覆盖数cnt>=k,则数目应该加上 区间长度*(cnt ...
- 初识Flutter
什么是Flutter 官网的定义如下: Flutter is a new project to help developers build high-performance, high-fidelit ...
- 并发编程5 操作系统&进程
一.今日大纲 1.multiprocessing模块简单应用 2.for循环创建进程 3.进程传参方式和创建方式2 4.join方法 5.操作系统基础 二.今日内容 (1)操作系统简单介绍 多道技术: ...
- PAGELATCH_x和PAGEIOLATCH_x介绍
Microsoft SQL Server企业级平台管理实践 第11章 Buffer Latch Timeout的解析 什么是PAGELATCH和PAGEIOLATCH 1.PAGELATCH_x和PA ...
- Android图片加载框架Picasso最全使用教程2
前言 前面我们已经介绍了Picasso的基本用法及如何将一张图片加载到ImageView中,下面我们就利用Picasso在ListView中加载图片;Let’s Go! 一个ListView的简单应用 ...
- Mac 启动和关闭rabbitmq
1.安装 brew install rabbitmq 2.启动及关闭RabbitMQ服务 前台启动 sudo ./rabbitmq-server 或 sudo su/usr/local/Cell ...
- 关于shared pool的深入探讨(一) 【转载】
关于shared pool的深入探讨(一) 作者:eygle |English [转载时请标明出处和作者信息]|[恩墨学院 OCM培训传DBA成功之道]链接:http://www.eygle.co ...
- C/C++中浮点数输出格式问题
在C语言中,浮点数的输出格式有三种:%g, %f, %e 首先要说的是%e是采用科学计数法来显示. %g与后两者有一个重要的差别,就是设置输出精度的时候,(C中默认浮点输出精度是6),%g认为,包括整 ...