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

NeuralVariable.dim()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 2
rs 10
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