MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / eye

Function eye

imperative/python/megengine/functional/tensor.py:184–227  ·  view source on GitHub ↗

r"""Returns a two-dimensional tensor with ones on the diagonal and zeros elsewhere. Args: N: number of rows in the output tesnor. M: number of columns in the output tesnor. If ``None``, the default number of columns in the output tesnor is equal tos ``N``. Keywo

(N: int, M: int = None, *, dtype="float32", device=None)

Source from the content-addressed store, hash-verified

182
183
184def eye(N: int, M: int = None, *, dtype="float32", device=None) -> Tensor:
185 r"""Returns a two-dimensional tensor with ones on the diagonal and zeros elsewhere.
186
187 Args:
188 N: number of rows in the output tesnor.
189 M: number of columns in the output tesnor.
190 If ``None``, the default number of columns in the output tesnor is equal tos ``N``.
191
192 Keyword args:
193 dtype(:attr:`.Tensor.dtype`, optional): output tesnor data type.
194 If ``None``, the output tesnor data type must be the default floating-point data type.
195 device(:attr:`.Tensor.device`, optional): device on which to place the created tensor.
196
197 .. seealso:: If you want to create a diagonal matrix, see :func:`~.functional.diag`.
198
199 Returns:
200 a tensor where all elements are equal to zero,
201 except for the diagonal, whose values are equal to one.
202
203 Examples:
204
205 >>> F.eye(3)
206 Tensor([[1. 0. 0.]
207 [0. 1. 0.]
208 [0. 0. 1.]], device=xpux:0)
209
210 >>> F.eye(4, 6)
211 Tensor([[1. 0. 0. 0. 0. 0.]
212 [0. 1. 0. 0. 0. 0.]
213 [0. 0. 1. 0. 0. 0.]
214 [0. 0. 0. 1. 0. 0.]], device=xpux:0)
215 """
216 if M is not None:
217 if isinstance(N, Tensor) or isinstance(M, Tensor):
218 shape = astensor1d((N, M))
219 else:
220 shape = Tensor([N, M], dtype="int32", device=device)
221 elif isinstance(N, Tensor):
222 shape = N
223 else:
224 shape = Tensor(N, dtype="int32", device=device)
225 op = builtin.Eye(k=0, dtype=dtype, comp_node=device)
226 (result,) = apply(op, shape)
227 return result
228
229
230def diag(inp, k: int = 0) -> Tensor:

Callers

nothing calls this directly

Calls 4

astensor1dFunction · 0.85
EyeMethod · 0.80
TensorClass · 0.50
applyFunction · 0.50

Tested by

no test coverage detected