张量转换为一键编码

时间:2018-09-08 12:02:29

标签: python numpy

我有一个window.geometry("1280x920+0+0")标量张量;我试图弄清楚如何使用NxTxW将其转换为一键编码。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用np.eye()和numpy切片:

def one_hot_encode(y):
    """Do one-hot encoding of y
    Parameters
    ----------

    y : numpy array of arbitrary shape

    Returns one-hot-encoded y of the same shape plus one-hot-encoded vector as
    a last axis
    """

    # map `y' to an index value (from 0 to number of classes minus one)
    y_vals = sorted(np.unique(y))
    K = len(y_vals)
    to_index = np.vectorize(lambda x: y_vals.index(x))
    y = to_index(y)

    # remove the last dimension since we want to substitute it with a one-hot-vector
    if y.shape[-1] == 1 and len(y.shape>1):
        y = y.reshape(y.shape[:-1])

    # do one hot encoding:
    y = np.eye(K)[y].astype( np.uint8 if K<255 else np.uint16 )
    return y