caffe入门classification00学习--ipython

首先,数据文件和模型文件都已经下载并处理好,不提。

cd   "caffe-root-dir "

----------------------------------分割线-------------------------------

# set up Python environment: numpy for numerical routines, and matplotlib for plotting
import numpy as np
import matplotlib.pyplot as plt
# display plots in this notebook
%matplotlib inline
--------------------------------------------------------------------------------------
# set display defaults
plt.rcParams[‘figure.figsize‘] = (10, 10)        # large images
plt.rcParams[‘image.interpolation‘] = ‘nearest‘  # don‘t interpolate: show square pixels
plt.rcParams[‘image.cmap‘] = ‘gray‘  # use grayscale output rather than a (potentially misleading) color heatmap

--------------------------------------------------------------------------------------

# The caffe module needs to be on the Python path;
#  we‘ll add it here explicitly.
import sys
caffe_root = ‘./‘  # this file should be run from {caffe_root}/examples (otherwise change this line)
sys.path.insert(0, caffe_root + ‘build/install/python‘)
--------------------------------------------------------------------------------------
import caffe
# If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path.

caffe.set_mode_cpu()
--------------------------------------------------------------------------------------
model_def = caffe_root + ‘models/bvlc_reference_caffenet/deploy.prototxt‘
model_weights = caffe_root + ‘models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel‘

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

--------------------------------------------------------------------------------------

# load the mean ImageNet image (as distributed with Caffe) for subtraction
mu = np.load(caffe_root + ‘build/install/python/caffe/imagenet/ilsvrc_2012_mean.npy‘)
mu = mu.mean(1).mean(1)  # average over pixels to obtain the mean (BGR) pixel values
print ‘mean-subtracted values:‘, zip(‘BGR‘, mu)

# create transformer for the input called ‘data‘
transformer = caffe.io.Transformer({‘data‘: net.blobs[‘data‘].data.shape})

transformer.set_transpose(‘data‘, (2,0,1))  # move image channels to outermost dimension
transformer.set_mean(‘data‘, mu)            # subtract the dataset-mean value in each channel
transformer.set_raw_scale(‘data‘, 255)      # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap(‘data‘, (2,1,0))  # swap channels from RGB to BGR

--------------------------------------------------------------------------------------

# set the size of the input (we can skip this if we‘re happy
#  with the default; we can also change it later, e.g., for different batch sizes)
net.blobs[‘data‘].reshape(50,        # batch size
                          3,         # 3-channel (BGR) images
                          227, 227)  # image size is 227x227

image = caffe.io.load_image(caffe_root + ‘examples/images/cat.jpg‘)
transformed_image = transformer.preprocess(‘data‘, image)
plt.imshow(image)

--------------------------------------------------------------------------------------

# copy the image data into the memory allocated for the net
net.blobs[‘data‘].data[...] = transformed_image

### perform classification
output = net.forward()

output_prob = output[‘prob‘][0]  # the output probability vector for the first image in the batch

print ‘predicted class is:‘, output_prob.argmax()

-----------------------------------------

# load ImageNet labels
labels_file = caffe_root + ‘data/ilsvrc12/synset_words.txt‘
if not os.path.exists(labels_file):
    !../data/ilsvrc12/get_ilsvrc_aux.sh
    
labels = np.loadtxt(labels_file, str, delimiter=‘\t‘)

print ‘output label:‘, labels[output_prob.argmax()]

----------------------------------------------------------------

# sort top five predictions from softmax output
top_inds = output_prob.argsort()[::-1][:5]  # reverse sort and take five largest items

print ‘probabilities and labels:‘
zip(output_prob[top_inds], labels[top_inds])

----------------------------------------------------------------

%timeit net.forward()

----------------------------------------------------------------

caffe.set_device(0)  # if we have multiple GPUs, pick the first one
caffe.set_mode_gpu()
net.forward()  # run once before timing to set up memory
%timeit net.forward()

----------------------------------------------------------------

# for each layer, show the output shape
for layer_name, blob in net.blobs.iteritems():
    print layer_name + ‘\t‘ + str(blob.data.shape)

----------------------------------------------------------------

for layer_name, param in net.params.iteritems():
    print layer_name + ‘\t‘ + str(param[0].data.shape), str(param[1].data.shape)

----------------------------------------------------------------

def vis_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)"""
    
    # normalize data for display
    data = (data - data.min()) / (data.max() - data.min())
    
    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = (((0, n ** 2 - data.shape[0]),
               (0, 1), (0, 1))                 # add some space between filters
               + ((0, 0),) * (data.ndim - 3))  # don‘t pad the last dimension (if there is one)
    data = np.pad(data, padding, mode=‘constant‘, constant_values=1)  # pad with ones (white)
    
    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.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, biases]
filters = net.params[‘conv1‘][0].data
vis_square(filters.transpose(0, 2, 3, 1))

----------------------------------------------------------------

feat = net.blobs[‘conv1‘].data[0, :36]
vis_square(feat)

----------------------------------------------------------------

feat = net.blobs[‘pool5‘].data[0]
vis_square(feat)

----------------------------------------------------------------

feat = net.blobs[‘fc6‘].data[0]
plt.subplot(2, 1, 1)
plt.plot(feat.flat)
plt.subplot(2, 1, 2)
_ = plt.hist(feat.flat[feat.flat > 0], bins=100)

----------------------------------------------------------------

feat = net.blobs[‘prob‘].data[0]
plt.figure(figsize=(15, 3))
plt.plot(feat.flat)

----------------------------------------------------------------

# download an image
my_image_url = "..."  # paste your URL here
# for example:
# my_image_url = "https://upload.wikimedia.org/wikipedia/commons/b/be/Orang_Utan%2C_Semenggok_Forest_Reserve%2C_Sarawak%2C_Borneo%2C_Malaysia.JPG"
!wget -O image.jpg $my_image_url

# transform it and copy it into the net
image = caffe.io.load_image(‘image.jpg‘)
net.blobs[‘data‘].data[...] = transformer.preprocess(‘data‘, image)

# perform classification
net.forward()

# obtain the output probabilities
output_prob = net.blobs[‘prob‘].data[0]

# sort top five predictions from softmax output
top_inds = output_prob.argsort()[::-1][:5]

plt.imshow(image)

print ‘probabilities and labels:‘
zip(output_prob[top_inds], labels[top_inds])

----------------------------------------------------------------

----------------------------------------------------------------

----------------------------------------------------------------

----------------------------------------------------------------

----------------------------------------------------------------

时间: 2024-10-13 00:30:16

caffe入门classification00学习--ipython的相关文章

Caffe入门随笔

Caffe入门随笔 分享一下自己入门机器学习的一些资料:(1)课程,最推荐Coursera上的Andrew NG的Machine Learning,最好注册课程,然后跟下来.其次是华盛顿大学的Machine Learning系列课程,一共有6门,包括毕业设计(2)书籍: 机器学习(周志华西瓜书).机器学习实战.统计学习方法(李航).集体智慧编程.数学之美(吴军)(3)微博@余凯_西二旗民工:@老师木:@梁斌penny:@张栋_机器学习:@邓侃:@大数据皮东:@djvu9:@陈天奇怪(4)知乎@贾

问题集录--新手入门深度学习,选择TensorFlow 好吗?

新手入门深度学习,选择 TensorFlow 有哪些益处? 佟达:首先,对于新手来说,TensorFlow的环境配置包装得真心非常好.相较之下,安装Caffe要痛苦的多,如果还要再CUDA环境下配合OpenCV使用,对于新手来说,基本上不折腾个几天是很难搞定的. 其次,基于TensorFlow的教学资源非常多,中英文的都有,这对于新手也是非常有帮助的.Google做社区非常有一套,在中国有专门的一群人,会在第一时间把Google的开发者相关的进展翻译成中文. 另外,由于有Google背书,Ten

【Zigbee技术入门教程-01】Zigbee无线组网技术入门的学习路线

[Zigbee技术入门教程-01]Zigbee无线组网技术入门的学习路线 广东职业技术学院  欧浩源 一.引言    在物联网技术应用的知识体系中,Zigbee无线组网技术是非常重要的一环,也是大家感觉比较难以掌握的一个部分.Zigbee无线组网技术之所以让你感有学习难度,不是因为它真的复杂,而是它看起来很复杂,让人望而止步.另一方面则是Zigbee技术在应用层面上将硬件和软件完成融为一个体系,要求开发人员既要有扎实的硬件技术,又要有清晰的软件思维.    目前,尽管有不少关于Zigbee无线组

如何快速入门Python学习呢?

根据TIOBE最新排名 ,Python已超越C#,与Java,C,C++一起成为全球前4大最流行语言,成为互联网时代最受欢迎的编程语言,越来越多的人选择Python,那么如何快速入门Python学习呢?首先你要了解Python,我们从以下几个方面来说. 学完python前景会咋样 其实我个人是很看好python未来的就业前景的,因为我认识太多的工程师都已经在学python,很多都是月收入大几万的 一项专业调查显示,75%的受访者将Python视为他们的主要开发语言,反之,其他25%受访者则将其视

如何入门深度学习?

Tel-Aviv大学深度学习实验室的Ofir同学写了一篇如何入门深度学习的文章,顺手翻译一下,造福生物信息狗. 人工神经网络最近在很多领域(例如面部识别,物体发现和围棋)都取得了突破,深度学习变得炙手可热.如果你对深度学习感兴趣的话,这篇文章是个不错的起点. 如果你学过线性代数,微积分,概率论和编程,我建议你从斯坦福大学的CS231n课程开始.这门课内容广泛,写得很高.可每次课的幻灯片都可以下载,虽然官方网站删除了配套的视频,但是你很容易就能在网上搜索到. 如果你没有学过那些数学课,网上也有很多

caffe源码学习之Proto数据格式【1】

前言: 由于业务需要,接触caffe已经有接近半年,一直忙着阅读各种论文,重现大大小小的模型. 期间也总结过一些caffe源码学习笔记,断断续续,这次打算系统的记录一下caffe源码学习笔记,巩固一下C++,同时也梳理一下自己之前的理解. 正文: 我们先不看caffe的框架结构,先介绍一下caffe.proto,是google开源的一种数据交互格式--Google Protobuf,这种数据的格式,我们可以看到caffe.proto中内容: syntax = "proto2"; pac

Webpack新手入门教程(学习笔记)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; font: 30.0px Helvetica; color: #000000 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px "PingFang TC Semibold"; color: #000000 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0

<LINUX >bash shell 入门 --linux学习笔记

首先说下我个人对于shell的理解,我觉得shell是一种通过各种控制语句将linux命令进行集合实现批处理的一种脚本语言. shell编程入门其实很简单,语法知识并不多,但是高级shell编程就很难,因为shell是用户和linux之间的桥梁,要编写高质量的shell脚本,就需要用户对linux有很全面的认识. 这里我们只分析shell脚本的语法知识,如想透彻的学习linux还需多努力. shell结构       1.#!指定执行脚本的shell 2.#注释行 3.命令和控制结构 创建she

由LCS到编辑距离—动态规划入门—算法学习笔记

一切计算机问题,解决方法可以归结为两类:分治和封装.分治是减层,封装是加层. 动态规划问题同样可以用这种思路,分治. 它可以划分为多个子问题解决,那这样是不是用简单的递归就完成了?也许是的,但是这样会涉及太多的不便的操作.因为子问题有重叠! 针对这种子问题有重叠的情况的解决,就是提高效率的关键. 所以动态规划问题可以总结为:最优子结构和重叠子问题. 解决这个子问题的方式的关键就是:memoization,备忘录. 动态规划算法分以下4个步骤: 描述最优解的结构 递归定义最优解的值 按自底向上的方