假设我有一个长度为30的向量x = [0.1, 0.2, 0.1, 0.1, 0.2, 0.4]
。这个向量由theano Tensor包裹。
我想创建一个与x
大小相同的新向量,但是将每个3个大小的切片元素设置为它们的总和,然后对接下来的3个元素执行相同操作,依此类推。
在该示例中,第一个3长度切片总和为0.4,第二个长度为0.7 r = [0.4, 0.4, 0.4, 0.7, 0.7, 0.7]
。
我该怎么做?是唯一使用scan
的方法吗?
答案 0 :(得分:2)
您可以在numpy中执行以下操作:
import numpy as np
x = np.array([0.1, 0.2, 0.1, 0.1, 0.2, 0.4])
y = (x.reshape(-1, 3).mean(1)[:, np.newaxis] * np.ones(3)).ravel()
print(y)
在theano中,您可以采用非常类似的方式继续:
import theano
import theano.tensor as T
xx = T.fvector()
yy = (xx.reshape((-1, 3)).mean(axis=1).reshape((-1, 1)) * T.ones(3)).ravel()
print(yy.eval({xx: x.astype('float32')}))