【发布时间】:2020-09-09 09:45:15
【问题描述】:
我有一个大小为torch.Size([8, 768]) 的词嵌入(张量类型)存储在变量embeddings 中,看起来像这样:-
tensor([[-0.0687, -0.1327, 0.0112, ..., 0.0715, -0.0297, -0.0477],
[ 0.0115, -0.0029, 0.0323, ..., 0.0277, -0.0297, -0.0599],
[ 0.0760, 0.0788, 0.1640, ..., 0.0574, -0.0805, 0.0066],
...,
[-0.0110, -0.1773, 0.1143, ..., 0.1397, 0.3021, 0.1670],
[-0.1379, -0.0294, -0.0026, ..., -0.0966, -0.0726, 0.1160],
[ 0.0466, -0.0113, 0.0283, ..., -0.0735, 0.0496, 0.0963]],
grad_fn=<IndexBackward>)
现在,我希望取一些嵌入的平均值并将平均值放回张量中。 例如,(我会用list而不是tensor来解释)
a = [1,2,3,4,5]
output = [1.5, 3, 4, 5]
所以,我在这里取了 1 和 2 的平均值,然后通过将元素移到列表中的左侧将其放入 list output。我也想对张量做同样的事情。
我将索引存储在变量i 中,我需要从中取平均值,j 变量用于停止索引。现在,让我们看一下代码:-
if i != len(embeddings):
sum = 0
count = 0
#Calculating sum
for x in range(i-1, j):
sum += text_index[x]
count += 1
avg = sum/count
#Inserting the average in place of the other embeddings
embeddings = embeddings[:i-1] + [avg] + embeddings[j:]
else :
pass
现在,我在这一行遇到错误embeddings = embeddings[:i-1] + [avg] + embeddings[j:]
错误是:-
TypeError: unsupported operand type(s) for +: 'Tensor' and 'list'
现在,我知道如果embeddings 是一个列表但它是一个张量,上面的代码会运行良好。我该怎么做?
注意:
*1。 *embeddings.shape : torch.Size([8, 768])
2. avg 是浮点型**
【问题讨论】: