Completed
Push — master ( f73e69...91b7c0 )
by Raphael
01:35
created

NeuralVariable   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 44
rs 10
c 1
b 0
f 0
wmc 12

9 Methods

Rating   Name   Duplication   Size   Complexity  
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 7 3
A set_test_value() 0 2 1
A getitem_wrapper() 0 5 2
A __init__() 0 9 2
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
        return getitem_wrapper(self, index)
30
31
    def apply(self, func, dim=None):
32
        """
33
        Apply a function to tensors.
34
        """
35
        output_dim = dim if dim else self.output_dim
36
        return NeuralVariable(func(self.tensor), func(self.test_tensor), output_dim)
37
38
    def compute_tensor(self, x):
39
        return self.tensor
40
41
    def compute_test_tesnor(self, x):
42
        return self.test_tensor
43
44
    def set_test_value(self, value):
45
        self.tensor.tag.test_value = value
46
47
    def dim(self):
48
        return self.output_dim
49
50
    def shape(self, dim_index):
51
        return NeuralVariable(self.tensor.shape[dim_index], self.test_tensor.shape[dim_index])
52