[pytest] basic test of Python layer
authorJonathan L Long <jonlong@cs.berkeley.edu>
Thu, 8 Jan 2015 00:36:35 +0000 (16:36 -0800)
committerJonathan L Long <jonlong@cs.berkeley.edu>
Tue, 17 Feb 2015 06:47:30 +0000 (22:47 -0800)
python/caffe/test/test_python_layer.py [new file with mode: 0644]

diff --git a/python/caffe/test/test_python_layer.py b/python/caffe/test/test_python_layer.py
new file mode 100644 (file)
index 0000000..cfb1d83
--- /dev/null
@@ -0,0 +1,62 @@
+import unittest
+import tempfile
+import os
+
+import caffe
+
+class SimpleLayer(caffe.Layer):
+    """A layer that just multiplies by ten"""
+
+    def setup(self, bottom, top):
+        pass
+
+    def reshape(self, bottom, top):
+        top[0].reshape(bottom[0].num, bottom[0].channels, bottom[0].height,
+                bottom[0].width)
+
+    def forward(self, bottom, top):
+        top[0].data[...] = 10 * bottom[0].data
+
+    def backward(self, top, propagate_down, bottom):
+        bottom[0].diff[...] = 10 * top[0].diff
+
+def python_net_file():
+    f = tempfile.NamedTemporaryFile(delete=False)
+    f.write("""name: 'pythonnet' force_backward: true
+    input: 'data' input_dim: 10 input_dim: 9 input_dim: 8 input_dim: 7
+    layers { type: PYTHON name: 'one' bottom: 'data' top: 'one'
+      python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }
+    layers { type: PYTHON name: 'two' bottom: 'one' top: 'two'
+      python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }
+    layers { type: PYTHON name: 'three' bottom: 'two' top: 'three'
+      python_param { module: 'test_python_layer' layer: 'SimpleLayer' } }""")
+    f.close()
+    return f.name
+
+class TestPythonLayer(unittest.TestCase):
+    def setUp(self):
+        net_file = python_net_file()
+        self.net = caffe.Net(net_file)
+        os.remove(net_file)
+
+    def test_forward(self):
+        x = 8
+        self.net.blobs['data'].data[...] = x
+        self.net.forward()
+        for y in self.net.blobs['three'].data.flat:
+            self.assertEqual(y, 10**3 * x)
+
+    def test_backward(self):
+        x = 7
+        self.net.blobs['three'].diff[...] = x
+        self.net.backward()
+        for y in self.net.blobs['data'].diff.flat:
+            self.assertEqual(y, 10**3 * x)
+
+    def test_reshape(self):
+        s = 4
+        self.net.blobs['data'].reshape(s, s, s, s)
+        self.net.forward()
+        for blob in self.net.blobs.itervalues():
+            for d in blob.data.shape:
+                self.assertEqual(s, d)