gpt4 book ai didi

python - 从索引列表到单热矩阵

转载 作者:太空狗 更新时间:2023-10-30 02:30:58 24 4
gpt4 key购买 nike

Theano 中将索引向量转换为零和一矩阵的最佳(优雅且高效)方法是什么,其中每一行都是索引的 N 表示之一?

v = t.ivector()  # the vector of indices
n = t.scalar() # the width of the matrix
convert = <your code here>
f = theano.function(inputs=[v, n], outputs=convert)

例子:

n_val = 4
v_val = [1,0,3]
f(v_val, n_val) = [[0,1,0,0],[1,0,0,0],[0,0,0,1]]

最佳答案

我没有比较不同的选项,但你也可以这样做。它不要求额外的内存。

import numpy as np
import theano

n_val = 4
v_val = np.asarray([1,0,3])
idx = theano.tensor.lvector()
z = theano.tensor.zeros((idx.shape[0], n_val))
one_hot = theano.tensor.set_subtensor(z[theano.tensor.arange(idx.shape[0]), idx], 1)
f = theano.function([idx], one_hot)
print f(v_val)[[ 0. 1. 0. 0.]
[ 1. 0. 0. 0.]
[ 0. 0. 0. 1.]]

关于python - 从索引列表到单热矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com