This repository was archived by the owner on Nov 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathinitialization.py
More file actions
202 lines (184 loc) · 7.94 KB
/
initialization.py
File metadata and controls
202 lines (184 loc) · 7.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# Copyright 2019 The TensorNetwork Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Functions to initialize Tensor using a NumPy-like syntax."""
import warnings
from typing import Optional, Sequence, Tuple, Any, Union, Type, Callable, List
from typing import Text
import numpy as np
from tensornetwork.backends import abstract_backend
from tensornetwork import backend_contextmanager
from tensornetwork import backends
from tensornetwork.tensor import Tensor
AbstractBackend = abstract_backend.AbstractBackend
def initialize_tensor(fname: Text,
*fargs: Any,
backend: Optional[Union[Text, AbstractBackend]] = None,
**fkwargs: Any) -> Tensor:
"""Return a Tensor wrapping data obtained by an initialization function
implemented in a backend. The Tensor will have the same shape as the
underlying array that function generates, with all Edges dangling.
This function is not intended to be called directly, but doing so should
be safe enough.
Args:
fname: Name of the method of backend to call (a string).
*fargs: Positional arguments to the initialization method.
backend: The backend or its name.
**fkwargs: Keyword arguments to the initialization method.
Returns:
tensor: A Tensor wrapping data generated by
(the_backend).fname(*fargs, **fkwargs), with one dangling edge per
axis of data.
"""
if backend is None:
backend = backend_contextmanager.get_default_backend()
backend_obj = backends.backend_factory.get_backend(backend)
func = getattr(backend_obj, fname)
data = func(*fargs, **fkwargs)
tensor = Tensor(data, backend=backend)
return tensor
def eye(N: int,
dtype: Optional[Type[np.number]] = None,
M: Optional[int] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor representing a 2D array with ones on the diagonal and
zeros elsewhere. The Tensor has two dangling Edges.
Args:
N (int): The first dimension of the returned matrix.
dtype, optional: dtype of array (default np.float64).
M (int, optional): The second dimension of the returned matrix.
backend (optional): The backend or its name.
Returns:
I : Tensor of shape (N, M)
Represents an array of all zeros except for the k'th diagonal of all
ones.
"""
the_tensor = initialize_tensor("eye", N, backend=backend, dtype=dtype, M=M)
return the_tensor
def zeros(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of all zeros.
The Tensor has one dangling Edge per dimension.
Args:
shape : Shape of the array.
dtype, optional: dtype of array (default np.float64).
backend (optional): The backend or its name.
Returns:
the_tensor : Tensor of shape `shape`. Represents an array of all zeros.
"""
the_tensor = initialize_tensor("zeros", shape, backend=backend, dtype=dtype)
return the_tensor
def ones(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of all ones.
The Tensor has one dangling Edge per dimension.
Args:
shape : Shape of the array.
dtype, optional: dtype of array (default np.float64).
backend (optional): The backend or its name.
Returns:
the_tensor : Tensor of shape `shape`
Represents an array of all ones.
"""
the_tensor = initialize_tensor("ones", shape, backend=backend, dtype=dtype)
return the_tensor
def ones_like(tensor: Union[Any],
dtype: Optional[Type[Any]] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor shape full of ones the same shape as input
Args:
tensor : Object to receive shape from
dtype (optional) : dtype of object
backend(optional): The backend or its name."""
if backend is None:
backend = backend_contextmanager.get_default_backend()
else:
backend = backend_contextmanager.backend_factory.get_backend(backend)
if isinstance(tensor, Tensor):
the_tensor = initialize_tensor("ones", tensor.shape,
backend=tensor.backend, dtype=tensor.dtype)
else:
try:
tensor = backend.convert_to_tensor(tensor)
except TypeError as e:
error = "Input to zeros_like has invalid type causing " \
"error massage: \n" + str(e)
raise TypeError(error) from e
the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(),
backend=backend, dtype=dtype)
return the_tensor
def zeros_like(tensor: Union[Any],
dtype: Optional[Any] = None,
backend: Optional[Union[Text,
AbstractBackend]] = None) -> Tensor:
"""Return a Tensor shape full of zeros the same shape as input
Args:
tensor : Object to receive shape from
dtype (optional) : dtype of object
backend(optional): The backend or its name."""
if backend is None:
backend = backend_contextmanager.get_default_backend()
else:
backend = backend_contextmanager.backend_factory.get_backend(backend)
if isinstance(tensor, Tensor):
the_tensor = initialize_tensor("zeros", tensor.shape,
backend=tensor.backend, dtype=tensor.dtype)
else:
try:
tensor = backend.convert_to_tensor(tensor)
except TypeError as e:
error = "Input to zeros_like has invalid " \
"type causing error massage: \n" + str(e)
raise TypeError(error) from e
the_tensor = initialize_tensor("zeros", tensor.shape,
backend=backend, dtype=dtype)
return the_tensor
def randn(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
seed: Optional[int] = None,
backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor:
"""Return a Tensor of shape `shape` of Gaussian random floats.
The Tensor has one dangling Edge per dimension.
Args:
shape : Shape of the array.
dtype, optional: dtype of array (default np.float64).
seed, optional: Seed for the RNG.
backend (optional): The backend or its name.
Returns:
the_tensor : Tensor of shape `shape` filled with Gaussian random data.
"""
the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed,
dtype=dtype)
return the_tensor
def random_uniform(shape: Sequence[int],
dtype: Optional[Type[np.number]] = None,
seed: Optional[int] = None,
boundaries: Optional[Tuple[float, float]] = (0.0, 1.0),
backend: Optional[Union[Text, AbstractBackend]]
= None) -> Tensor:
"""Return a Tensor of shape `shape` of uniform random floats.
The Tensor has one dangling Edge per dimension.
Args:
shape : Shape of the array.
dtype, optional: dtype of array (default np.float64).
seed, optional: Seed for the RNG.
boundaries : Values lie in [boundaries[0], boundaries[1]).
backend (optional): The backend or its name.
Returns:
the_tensor : Tensor of shape `shape` filled with uniform random data.
"""
the_tensor = initialize_tensor("random_uniform", shape, backend=backend,
seed=seed, boundaries=boundaries, dtype=dtype)
return the_tensor