Completed
Push — master ( e28af2...662c2c )
by Raphael
01:46
created

NeuralVariable   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 54
rs 10
wmc 14

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getitem_wrapper() 0 5 2
A __init__() 0 9 2
A compute_test_tesnor() 0 2 1
A compute_tensor() 0 2 1
A apply() 0 6 2
A shape() 0 2 1
A dim() 0 2 1
A __getitem__() 0 9 3
A set_test_value() 0 2 1
A __call__() 0 2 1
A __getattr__() 0 2 1
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
from layer import NeuralLayer
5
from deepy.utils.decorations import neural_computation
6
7
8
class NeuralVariable(NeuralLayer):
9
    """
10
    Create a constant layer with tensors.
11
    """
12
13
    def __init__(self, tensor, test_tensor=None, dim=0):
14
        """
15
        Create a tensor layer.
16
        """
17
        super(NeuralVariable, self).__init__("const")
18
        self.output_dim = dim
19
        self.tensor = tensor
20
        self.test_tensor = tensor if not test_tensor else test_tensor
21
        self.initialize(0)
22
23
    def __getitem__(self, index):
24
        @neural_computation
25
        def getitem_wrapper(t, index):
26
            if type(index) == list:
27
                index = tuple(index)
28
            return t.__getitem__(index)
29
        ret = getitem_wrapper(self, index)
30
        ret.output_dim = self.dim()
31
        return ret
32
33
    def __call__(self, *args, **kwargs):
34
        return NeuralVariable(self.tensor(*args, **kwargs), self.test_tensor(*args, **kwargs), dim=self.dim())
35
36
    def __getattr__(self, name):
37
        return NeuralVariable(getattr(self.tensor, name), getattr(self.test_tensor, name), dim=self.dim())
38
39
40
41
    def apply(self, func, dim=None):
42
        """
43
        Apply a function to tensors.
44
        """
45
        output_dim = dim if dim else self.output_dim
46
        return NeuralVariable(func(self.tensor), func(self.test_tensor), output_dim)
47
48
    def compute_tensor(self, x):
49
        return self.tensor
50
51
    def compute_test_tesnor(self, x):
52
        return self.test_tensor
53
54
    def set_test_value(self, value):
55
        self.tensor.tag.test_value = value
56
57
    def dim(self):
58
        return self.output_dim
59
60
    def shape(self, dim_index):
61
        return NeuralVariable(self.tensor.shape[dim_index], self.test_tensor.shape[dim_index])
62