caffe2-- Workspaces(二)

来源:互联网 发布:opencv2 分水岭算法 编辑:程序博客网 时间:2024/05/23 19:52

这篇教程介绍caffe2的基本组成部分:

  1. Workspaces
  2. Operators
  3. Nets

开始之前,回顾一下以前的教程。

浏览教程

在本教程中,我们将介绍一系列的Caffe2基础知识:基本概念,包括操作符和网络的编写方式。

首先,导入caffe2.core和workspace,这两个通常是我们最需要的。如果你想要操作由caffe2生成的protocol buffers ,你需要从caffe2.proto中导入caffe2_pb2。

#导入其他的标准库from matplotlib import pyplotimport numpy as npimport time#These are the droids you are looking for.from caffe2.python import core,workspacefrom caffe2.proto import caffe2_pb2# Let's show all plots inline.@matplotlib inline

Workspaces

首先,介绍所有数据所在的工作区。

如果您熟悉Matlab,工作区将由您创建并存储在内存中的Blob组成。 现在,考虑一个Blob是一个类似于numpy的ndarray的N维Tensor,但是是连续的。 在路上,我们会告诉你,一个blob实际上是一个可以存储任何类型的C ++对象的类型化指针,但是Tensor是存储在blob中的最常见的类型。 让我们来看以下接口。

Blobs()打印工作区内已经存在的所有blobs。HasBlob()查询工作区是否有一个blob存在。

print("Current blobs in the workspace:{}".format(workspace.Blobs()))print("Workspace has blob 'X'?".format(workspace.HasBlob("X")))

We can feed blobs into the workspace using FeedBlob()

X=np.random.randn(2,3).astype(np.float32)print("Generated X from numpy:\n{}".format(X))workspace.FeedBlob("X",X)
Generated X from numpy:[[-0.56927377 -1.28052795 -0.95808828] [-0.44225693 -0.0620895  -0.50509363]]

现在来看一下在工作区有哪些blobs。

print("Current blobs in the workspace:{}".format(workspace.Blobs()))print("Workspace has blob 'X'.format(workspace.HasBlob("X")))print("Fetched X:\n{}".format(workspace.FetchBlob("X")))
Current blobs in the workspace: [u'X']Workspace has blob 'X'? TrueFetched X:[[-0.56927377 -1.28052795 -0.95808828] [-0.44225693 -0.0620895  -0.50509363]]

让我们来验证数组是相等的。

np.testing.assert_array_equal(X,workspace.FetchBlob("X"))

如果你尝试着访问一个不存在的blob,一个错误被抛出。

try:    workspace.FetchBlob("invincible_pink_unicorn")except RuntimeError as err:    print(err)
[enforce fail at pybind_state.cc:441] gWorkspace->HasBlob(name).

可以使用python创建多个工作区,blobs在不同的工作区是相互独立的,你可以使用CurrentWorkspace来查看你目前的工作区,尝试通过工作区名字来切换工作区,如果工作区不存在那就创建一个。

print("Current workspace: {}".format(workspace.CurrentWorkspace()))print("Current blobs in the workspace: {}".format(workspace.Blobs()))# Switch the workspace. The second argument "True" means creating# the workspace if it is missing.workspace.SwitchWorkspace("gutentag", True)# Let's print the current workspace. Note that there is nothing in the# workspace yet.print("Current workspace: {}".format(workspace.CurrentWorkspace()))print("Current blobs in the workspace: {}".format(workspace.Blobs()))
Current workspace: defaultCurrent blobs in the workspace: ['X']Current workspace: gutentagCurrent blobs in the workspace: []

Let’s switch back to the default workspace.

workspace.SwitchWorkspace("default")print("Current workspace: {}".format(workspace.CurrentWorkspace()))print("Current blobs in the workspace: {}".format(workspace.Blobs()))```最后,ResetWorkspace()清除目前工作区里的内容。

workspace.ResetWorkspace()
“`

原创粉丝点击