如何使用ano中的scan函数迭代一个ano矩阵的行?

2024-06-16 03:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的代码来计算一个索引列表的热编码。 例如:[1,2,3]=>;[[0,1,0,0],[0,0,1,0],[0,0,0,1]]

我编写了一个函数来对单个向量执行相同的操作:

n_val =4
def encoding(x_t):
    z = T.zeros((x_t.shape[0], n_val))
    one_hot = T.set_subtensor(z[T.arange(x_t.shape[0]), x_t], 1)
    return one_hot

要在矩阵的行上重复同样的函数,我做如下操作

^{pr2}$

我期望一个三维张量,每个切片对应于矩阵行的一个热编码。在

我在编译函数时遇到以下错误

/Library/Python/2.7/site-packages/theano/tensor/var.pyc in __iter__(self)
594         except TypeError:
595             # This prevents accidental iteration via builtin.sum(self)
--> 596             raise TypeError(('TensorType does not support iteration. '
    597                              'Maybe you are using builtin.sum instead of '
598                              'theano.tensor.sum? (Maybe .max?)'))

TypeError: TensorType does not support iteration. Maybe you are using builtin.sum instead of theano.tensor.sum? (Maybe .max?)

有人能帮我理解我哪里出错了,我如何修改代码来获得我需要的东西?在

提前谢谢。在


Tags: 函数代码编码矩阵valtheanoonesum
1条回答
网友
1楼 · 发布于 2024-06-16 03:31:07

这是有效的代码

# input a matrix, expect scan to work with each row of matrix
my_matrix = np.asarray([[1,2,3],[1,3,2],[1,1,1]])

x = T.imatrix()

def encoding(idx):
    z = theano.tensor.zeros((idx.shape[0], 4))
    one_hot = theano.tensor.set_subtensor(z[theano.tensor.arange(idx.shape[0]), idx], 1)
    return one_hot

m, update = theano.scan(fn=encoding,
                        sequences=x)


f = theano.function([x], m)

##########3
result = f(my_matrix)
print (result)

相关问题 更多 >