siteground建站教程品牌seo是什么意思
index_add?
paddle.index_add(x,?index,?axis,?value,?name=None)[源代碼]?
沿著指定軸?axis
?將?index
?中指定位置的?x
?與?value
?相加,并寫入到結果 Tensor 中的對應位置。這里?index
?是一個?1-D
?Tensor。除?axis
?軸外,返回的 Tensor 其余維度大小和輸入?x
?相等,?axis
?維度的大小等于?index
?的大小。
官方文檔:index_add-API文檔-PaddlePaddle深度學習平臺
我們還是通過一個代碼示例來學習:
x = paddle.ones([5, 3])
value = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=paddle.float32)
index = paddle.to_tensor([0, 4, 2])
print(x)x = paddle.index_add(x, index, 0, value)
print(x)
?輸出
Tensor(shape=[5, 3], dtype=float32, place=Place(cpu), stop_gradient=True,[[1., 1., 1.],[1., 1., 1.],[1., 1., 1.],[1., 1., 1.],[1., 1., 1.]]) Tensor(shape=[5, 3], dtype=float32, place=Place(cpu), stop_gradient=True,[[2. , 3. , 4. ],[1. , 1. , 1. ],[8. , 9. , 10.],[1. , 1. , 1. ],[5. , 6. , 7. ]])
API 解析:index_add
查看前面的例子輸出,可以看到,index_add就是把value的各個值,按照index里的值為索引,加入到源x里面去,比如
value = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=paddle.float32)
index = paddle.to_tensor([0, 4, 2])
首先取出value[0] ,發(fā)現(xiàn)index[0]是?0,那么就把value[0] 跟x[0]相加
取出value[1] ,發(fā)現(xiàn)index[1] 是4,那么就把value[1] 跟x[4]相加
取出value[2] ,發(fā)現(xiàn)index[2] 是2,那么就把value[2] 跟x[2]相加
在飛槳官方?jīng)]有index_add函數(shù)的時候,可以用python來實現(xiàn),當然速度會慢很多:
def paddleindex_add(x, dim, index, source): # 飛槳的index_add'''
x = paddle.ones([5, 3])
t = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=paddle.float32)
index = paddle.to_tensor([0, 4, 2])
# print(x)
with Benchmark("paddleindex_add"):x = paddleindex_add(x, 0, index, t)
print(x)'''for i in range(len(index)):x[index[i]] += source[i]return x
可以從賦值語句看到,就是從index里面取出值,然后x和source的相關值相加:x[index[i]] += source[i]
當然注釋里面用了Benchmark函數(shù),抄李沐老師的,源碼如下
import time
class Timer: #@save"""記錄多次運行時間"""def __init__(self):self.times = []self.start()def start(self):"""啟動計時器"""self.tik = time.time()def stop(self):"""停止計時器并將時間記錄在列表中"""self.times.append(time.time() - self.tik)return self.times[-1]def avg(self):"""返回平均時間"""return sum(self.times) / len(self.times)def sum(self):"""返回時間總和"""return sum(self.times)def cumsum(self):"""返回累計時間"""return np.array(self.times).cumsum().tolist()class Benchmark:"""用于測量運行時間"""def __init__(self, description='Done'):self.description = descriptiondef __enter__(self):self.timer = Timer()return selfdef __exit__(self, *args):print(f'{self.description}: {self.timer.stop():.4f} sec')