OnehotOperation
Description
One-hot encoding.
Operator Function Implementation
One of the preprocessing encoding modes of machine learning: onehot encoding. In onehot encoding, depth states are encoded, a corresponding position of each state is set to 1, and other positions are set to 0. A result is a vector with only one bit being 1 and a length being depth.
The operator outputs the one-hot encoding corresponding to each element of the input tensor x. The result is that the dimension depth is added to the axis position.
Computational process (Python):
res = np.eye(depth)[input0]
Example 1 (Python):
x shape: torch.Size([2, 3])
x: tensor([[4, 4, 6],
[6, 7, 6]])
depth: 10
axis: -1
# If axis is -1, the last dimension output[i][j][:] is the onehot code corresponding to x[i][j].
out_tensor shape: torch.Size([2, 3, 10])
out_tensor: tensor([[[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]],
[[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]]], device='npu:0')
Example 2 (Python):
x shape: torch.Size([2, 3])
x: tensor([[2, 0, 4],
[4, 3, 0]])
depth: 5
axis: 0
# output[:][i][j] is the onehot code corresponding to x[i][j]. If axis is 1, output[i][:][j] is the onehot code corresponding to x[i][j].
out_tensor shape: torch.Size([5, 2, 3])
out_tensor: tensor([[[0, 1, 0],
[0, 0, 1]],
[[0, 0, 0],
[0, 0, 0]],
[[1, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 1, 0]],
[[0, 0, 1],
[1, 0, 0]]], device='npu:0')
Definition
struct OnehotParam {
int64_t axis = 0;
int64_t depth = 0;
uint8_t rsv[8] = {0};
};
Parameters
Member |
Type |
Default Value |
Description |
|---|---|---|---|
axis |
int64_t |
0 |
Index of depth. The value can be a negative number, indicating that the axis dimension counted from the end of output is the input onehot code. |
depth |
int64_t |
0 |
Length of the onehot code corresponding to each input. |
rsv[8] |
uint8_t |
{0} |
Reserved |
Input
Parameter |
Dimension |
Data Type |
Format |
Description |
|---|---|---|---|---|
x |
[-1,...,-1] The value -1 indicates that the size of the current dimension is not restricted. |
int32/int64 |
ND |
Input tensor, indicating the states of the onehot code to be obtained. |
one |
[1] |
int32/int64 Same as that of x |
ND |
Scalar 1. The type and format are the same as those of x. It is passed to the operator and has no actual meaning. |
zero |
[1] |
int32/int64 Same as that of x |
ND |
Scalar 0. The type and format are the same as those of x. It is passed to the operator and has no actual meaning. |
Output
Parameter |
Dimension |
Data Type |
Format |
Description |
|---|---|---|---|---|
output |
Compared with x, it has one more depth dimension on the axis. |
int32/int64 Same as that of x |
ND |
Output tensor. The type and format are the same as those of x. The output is a onehot code. |
Restrictions
- The absolute value of axis must be less than the number of dimensions of x.
- The element in x is less than depth.