Pytorch求向量的L1范数或L2范数
生活随笔
收集整理的這篇文章主要介紹了
Pytorch求向量的L1范数或L2范数
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、向量/張量
? ? ? ? 向量是一維的張量,而張量可以理解為一個(gè)樹(shù)形結(jié)構(gòu)的數(shù)據(jù)。例如,向量
? ? ? ? 所對(duì)應(yīng)的樹(shù)形結(jié)構(gòu)數(shù)據(jù)為
? ? ? ? 其中,vector節(jié)點(diǎn)是dim=0的張量,對(duì)應(yīng)樹(shù)高為0,節(jié)點(diǎn)1.0、2.0等是dim=1的張量,對(duì)應(yīng)樹(shù)高為1。根據(jù)定義,vector的L1范數(shù)和L2范數(shù)計(jì)算方式如下:
二、代碼+輸出
import torch# Pytorch求向量的L1范數(shù)或L2范數(shù) def tc04():# 向量(1維張量)vector = torch.tensor([1.0, 2.0, 3.0, 4.0, -5.0])# 求向量的L1范數(shù)norm1 = torch.norm(vector, p=1, dim=0)# 求向量的L2范數(shù)norm2 = torch.norm(vector, p=2, dim=0)print("The L1 norm of %s is %f. " % (str(vector), norm1.item()))print("The L2 norm of %s is %f. " % (str(vector), norm2.item()))# 程序入口 if __name__ == '__main__':tc04()? ? ? ? 輸出
The L1 norm of tensor([ 1., 2., 3., 4., -5.]) is 15.000000. The L2 norm of tensor([ 1., 2., 3., 4., -5.]) is 7.416198. Process finished with exit code 0總結(jié)
以上是生活随笔為你收集整理的Pytorch求向量的L1范数或L2范数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 微信小程序: wx:key详解
- 下一篇: 你需要来自TrustedInstalle