在本教程中,我们将介绍一系列的Caffe2基础知识:基本概念,包括Op和net的编写方式。
首先,导入caffe2.core和workspace,这两个通常是我们最需要的。如果你想要操作由caffe2生成的protocol buffers ,你需要从caffe2.proto中导入caffe2_pb2。
#__future__一定要写在最前面
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals# We'll also import a few standard python libraries
from matplotlib import pyplot
import numpy as np
import time# These are the droids you are looking for.
from caffe2.python import core, workspace
from 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")))
用FeedBlob()将blobs加入到workspace
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:
[[-1.25644767 -0.59852821 1.70516002][ 0.31694144 0.76856893 0.09610417]]
现在再来看一下有什么blobs在workspace中
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'? True
Fetched X:
[[-1.25644767 -0.59852821 1.70516002][ 0.31694144 0.76856893 0.09610417]]
让我们来验证数组是相等的
np.testing.assert_array_equal(X,workspace.FetchBlob("X"))
如果你尝试着访问一个不存在的blob,一个错误被抛出。
try:workspace.FetchBlob("invincible_pink_unicorn")
except RuntimeError as err:print(err)
可以使用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: default
Current blobs in the workspace: ['X']
Current workspace: gutentag
Current blobs in the workspace: []
然后再转换会默认的workspace
workspace.SwitchWorkspace("default")
print("Current workspace :{}".format(workspace.CurrentWorkspace()))
print("Current blobs in the workspace :{}".format(workspace.Blobs()))
输出:
Current workspace: default
Current blobs in the workspace: [u'X'
最后,用ResetWorkspace()来清空当前space
workspace.ResetWorkspace()
print("Current blobs in the workspace after reset: {}".format(workspace.Blobs()))
Current blobs in the workspace after reset: []