【caffe】Caffe: (二) Classification (CPU/GPU设置, feature map可视化,层名,参数输出, Top-1、Top-5输出)

发布时间:2026/10/22 6:47:47

【caffe】Caffe: (二) Classification (CPU/GPU设置, feature map可视化,层名,参数输出, Top-1、Top-5输出) #set up python environment: numpy for numerical routines, matplotlib for plottingimportnumpyasnpimportmatplotlib.pyplotasplt#display plots in this notebook%matplotlib inlineplt.rcParams[figure.figsize](10,10)# large imagesplt.rcParams[image.interpolation]nearest# dont interpolate: show square pixelsplt.rcParams[image.cmap]gray#use grayscale output rather than a (potentially misleading) color hetmap# the caffe modules needs to be on the Python path:importsys# print(sys.path)importcaffeimportos caffe_rootpath to caffeimportosifos.path.exists(caffe_rootmodels/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel):print(CaffeNet found.)else:print(Downloading pre-trained caffenet model...)!path_to_caffe/scripts/download_model_binary.py path_to_caffe/models/bvlc_reference_caffenet/CaffeNet found.importsys# print(sys.path)caffe.set_mode_cpu()model_defcaffe_rootmodels/bvlc_reference_caffenet/deploy.prototxtmodel_weightscaffe_rootmodels/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel#define the structure of the model, trained weights, use test mdoenetcaffe.Net(model_def,model_weights,caffe.TEST)# load the mean ImageNet image (as distributed with Caffe) for subtractionmunp.load(caffe_rootpython/caffe/imagenet/ilsvrc_2012_mean.npy)mumu.mean(1).mean(1)#average over pixels to obtain the mean (BGR) pixel valuesprint(mean-subtracted values: ,list(zip(BGR,mu)))mean-subtracted values: [(B, 104.0069879317889), (G, 116.66876761696767), (R, 122.6789143406786)]# create transformer for the input called datatransformercaffe.io.Transformer({data:net.blobs[data].data.shape})transformer.set_transpose(data,(2,0,1))#move image channels to outermost dimensiontransformer.set_mean(data,mu)#subtract the dataset-mean value in each channeltransformer.set_raw_scale(data,255)#rescale from [0,1] to [0,255]transformer.set_channel_swap(data,(2,1,0))# set the size of the inputnet.blobs[data].reshape(50,3,227,227)imagecaffe.io.load_image(caffe_rootexamples/images/cat.jpg)transformed_imagetransformer.preprocess(data,image)plt.imshow(image)matplotlib.image.AxesImage at 0x7fe5fae03978# copy the image data into the memory allocated for the netnet.blobs[data].data[...]transformed_image# perform classificationoutputnet.forward()output_proboutput[prob][0]# the output probability vector for the first image in the batchprint(predicted class is: ,output_prob.argmax())predicted class is: 281# load ImageNet labelslabels_filecaffe_rootdata/ilsvrc12/synset_words.txtifnotos.path.exists(labels_file):!path_to_caffe/data/ilsvrc12/get_ilsvrc_aux.sh labelsnp.loadtxt(labels_file,str,delimiter\t)print(output label: ,labels[output_prob.argmax()])Downloading... --2020-03-04 13:47:08-- http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz Resolving dl.caffe.berkeleyvision.org (dl.caffe.berkeleyvision.org)... 128.32.162.150 Connecting to dl.caffe.berkeleyvision.org (dl.caffe.berkeleyvision.org)|128.32.162.150|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 17858008 (17M) [application/octet-stream] Saving to: ‘caffe_ilsvrc12.tar.gz’ caffe_ilsvrc12.tar. 100%[] 17.03M 111KB/s in 4m 15s 2020-03-04 13:51:25 (68.3 KB/s) - ‘caffe_ilsvrc12.tar.gz’ saved [17858008/17858008] Unzipping... Done. output label: n02123045 tabby, tabby cat# sort top five predictions from softmax outputtop_indsoutput_prob.argsort()[::-1][:5]print(probabilities and labels: )print(list(zip(output_prob[top_inds],labels[top_inds])))probabilities and labels: [(0.32925108, n02123045 tabby, tabby cat), (0.23463891, n02123159 tiger cat), (0.12834354, n02124075 Egyptian cat), (0.10341559, n02119022 red fox, Vulpes vulpes), (0.06193552, n02127052 lynx, catamount)]%timeit net.forward()768 ms ± 14.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)caffe.set_device(0)# if we have multiple GPUs, pick the first onecaffe.set_mode_gpu()net.forward()# run once before timing to set up memory%timeit net.forward()42.6 ms ± 63.2 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)# for each layer, show the outpyt shapeforlayer_name,blobinnet.blobs.items():print(layer_name\tstr(blob.data.shape))data (50, 3, 227, 227) conv1 (50, 96, 55, 55) pool1 (50, 96, 27, 27) norm1 (50, 96, 27, 27) conv2 (50, 256, 27, 27) pool2 (50, 256, 13, 13) norm2 (50, 256, 13, 13) conv3 (50, 384, 13, 13) conv4 (50, 384, 13, 13) conv5 (50, 256, 13, 13) pool5 (50, 256, 6, 6) fc6 (50, 4096) fc7 (50, 4096) fc8 (50, 1000) prob (50, 1000)forlayer_name,paraminnet.params.items():print(layer_name\tstr(param[0].data.shape),str(param[1].data.shape))conv1 (96, 3, 11, 11) (96,) conv2 (256, 48, 5, 5) (256,) conv3 (384, 256, 3, 3) (384,) conv4 (384, 192, 3, 3) (384,) conv5 (256, 192, 3, 3) (256,) fc6 (4096, 9216) (4096,) fc7 (4096, 4096) (4096,) fc8 (1000, 4096) (1000,)defvis_square(data):# Take an array of shape (n, height, width) or (n, height, width, 3)# and visualize each (height, width) thing in a grid of size approx.# sqrt(n) by sqrt(n)print(data.shape[0],data.shape[1],data.shape[2])# normalize data for displaydata(data-data.min())/(data.max()-data.min())# force the number of filters to be squarenint(np.ceil(np.sqrt(data.shape[0])))# add some space between filters# dont pad the last dimension (if there is one)padding(((0,n**2-data.shape[0]),(0,1),(0,1))((0,0),)*(data.ndim-3))print(padding)# pad with ones (white)datanp.pad(data,padding,modeconstant,constant_values1)# tile the filters into an imagedatadata.reshape((n,n)data.shape[1:]).transpose((0,2,1,3)tuple(range(4,data.ndim1)))datadata.reshape((n*data.shape[1],n*data.shape[3])data.shape[4:])plt.imshow(data)plt.axis(off)# the parameters are a list of [weights, bias]filtersnet.params[conv1][0].data vis_square(filters.transpose(0,2,3,1))96 11 11 ((0, 4), (0, 1), (0, 1), (0, 0))featnet.blobs[conv1].data[0,:36]vis_square(feat)36 55 55 ((0, 0), (0, 1), (0, 1))featnet.blobs[pool5].data[0]vis_square(feat)256 6 6 ((0, 0), (0, 1), (0, 1))featnet.blobs[fc6].data[0]plt.subplot(2,1,1)plt.plot(feat.flat)plt.subplot(2,1,2)_plt.hist(feat.flat[feat.flat0],bins100)理解总结部分设置CPU、GPU的方式cpu模式caffe.set_mode_cpu()gpu模式caffe.set_device(0)# if we have multiple GPUs, pick the first onecaffe.set_mode_gpu()分类Top-1 Top-5设置Top-1output_prob output[prob][0] # the output probability vector for the first image in the batchTop-5# sort top five predictions from softmax output top_inds output_prob.argsort()[::-1][:5]输出所有层的shape和对应参数的shape输出对应层的名字和shape,feature map 的方式 (N, C, H, W)# for each layer, show the outpyt shapeforlayer_name,blobinnet.blobs.items():print(layer_name\tstr(blob.data.shape))输出对应层参数的权重weights和biasesweights的存储方式output_channels, input_channels, filter_height, filter_widthforlayer_name,paraminnet.params.items():print(layer_name\tstr(param[0].data.shape),str(param[1].data.shape))可视化卷积核defvis_square(data):# Take an array of shape (n, height, width) or (n, height, width, 3)# and visualize each (height, width) thing in a grid of size approx.# sqrt(n) by sqrt(n)print(data.shape[0],data.shape[1],data.shape[2])# normalize data for displaydata(data-data.min())/(data.max()-data.min())# force the number of filters to be squarenint(np.ceil(np.sqrt(data.shape[0])))# add some space between filters# dont pad the last dimension (if there is one)padding(((0,n**2-data.shape[0]),(0,1),(0,1))((0,0),)*(data.ndim-3))print(padding)# pad with ones (white)datanp.pad(data,padding,modeconstant,constant_values1)# tile the filters into an imagedatadata.reshape((n,n)data.shape[1:]).transpose((0,2,1,3)tuple(range(4,data.ndim1)))datadata.reshape((n*data.shape[1],n*data.shape[3])data.shape[4:])plt.imshow(data)plt.axis(off)
延伸阅读

更多相关文章

2026/10/22 6:47:47

【Tensorflow实战系列】Tensorflow: 怎么写L2 loss

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/22 6:42:47

基于STM32F107和PJ85718DM的本地与远程温度监测系统

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/22 8:53:24

TCP长肥管道与RFC 1323调优实战指南

1. 什么是“长肥管道”?——从一次真实丢包事故说起 我第一次真正意识到“长肥管道”不是教科书里的抽象概念,是在某次为某高校实验室部署远程图像采集系统时。那套系统需要把高清显微镜视频流实时传回本地工作站,链路跨了三个省,…

2026/10/22 8:53:24

BiLSTM+Attention关系抽取实战:数据处理、模型实现与调参

如果你是第一次在NLP课程作业里撞上“BiLSTMAttention做关系抽取”这个组合,我的建议是别急着到处抄代码。这个题目看起来只是把两个经典模块拼在一起,但真正做完之后你会发现,它其实把文本分类、序列建模、注意力机制、数据处理、实验分析这…

2026/10/22 8:53:24

Dlib人脸检测实战:从原理到课堂签到系统的踩坑与调优

收到一个做课堂签到小项目的需求,思路很简单:摄像头拍到人,系统自动识别身份。真正动手第一步就卡住了——不是最后比对环节的多难,而是最前面的人脸检测一直不稳。起初用的OpenCV Haar级联检测器,教室白板上的挂钟、海…

2026/10/22 8:53:24

Unity冒险游戏开发:MB903可复用骨架源码解析

简介:本资源是基于Unity3D引擎开发的完整冒险类游戏项目MB903,面向游戏开发初学者与Unity进阶学习者,聚焦实战化3D游戏设计能力培养。项目涵盖角色战斗系统(含‘死亡骑士’‘地狱骑士’BOSS战设计)、禅达酒店起始场景、…

2026/10/22 8:53:24

从零构建第一个AI智能体:函数调用、主循环与避坑全记录

人生第一个AI智能体跑通的那一刻,我盯着终端里那句“好的,已帮你把明天的会议提醒加进待办”,愣了几秒。代码量并不大:一个循环、几张工具表、一段系统提示词,但它确实能听懂自然语言,自己决定查天气、记待…

2026/10/22 8:48:14

HDFS数据本地性如何决定MapReduce性能

1. 从“写入一个文件”开始:HDFS与MapReduce不是两张皮,而是一套动作的上下半场很多人一提HDFS就只想到“存东西”,一说MapReduce就只记得“跑计算”,结果学完半年还分不清为什么WordCount里先要hadoop fs -put再hadoop jar——仿…

2026/10/21 4:53:08

金融AI落地指南:从调研报告到技术选型与工程实践

简介:这份PDF报告聚焦2025年金融服务业中国AI现状与趋势,面向金融科技从业者、AI战略规划人员及关注行业数字化转型的研究者,帮助读者把握生成式AI在银行、支付、交易等场景中的落地路径与投资方向。资源包内含1个PDF文件,大小约1…

2026/10/22 0:01:49

电商智能运营体系从0到1:架构设计、落地步骤与避坑指南

前两年我们团队接了一个电商平台的运营中台项目,目标很直白:把过去靠运营拍脑袋做的选品、定价、发券、推活动这些事,逐步用数据算法和自动化流程代替。项目名字内部就叫“电商智能运营体系”。最近有不少朋友问我当时是怎么设计的、踩过哪些…

2026/10/22 0:01:49

若依框架AI代码生成不稳定?用Agent Skill三层结构+五步法搞定

最近一段时间,我一直想把后台管理系统里那些机械重复的增删改查代码交给AI去写。框架用的是若依,按理说这类业务代码模式非常固定,应该是AI最擅长的事情。可真试下来却不是那么回事——你让AI生成一个用户管理模块,它给出的Contro…

还想了解更多?直接咨询顾问

免费诊断 + 免费方案 + 透明报价。

全国咨询热线400-8866-253
免费获取方案
☎咨询二维码 ☎ ↑