1. 程式人生 > 實用技巧 >pytorch 使用tensor 計算歐氏距離

pytorch 使用tensor 計算歐氏距離

如何建立Python (安裝Anaconda)的執行環境

Python 基礎教程--直譯器的建立和配置

以建立anaconda為例

======================================================================

(For more information, please go to
Alan D. Chen , upgrading~~)

Thanks a lot to Ms Wang QianQian for her help with this Blog!

眾所周知,GPU的執行速度遠大於CPU的速度。 You can go to

this web.

`import numpy
as np import time import torch import torch.nn.functional as F

a = np.random.rand(1,1000000)
b = np.random.rand(1,1000000)
c = torch.rand(1,1000000)
d = torch.rand(1,1000000)
e = torch.rand(1,1000000).cuda()
f = torch.rand(1,1000000).cuda()

計算numpy計算速度

time_start=time.time()
dist1 = np.linalg.norm(a - b)#numpy求歐氏距離
time_end=time.time()
print(time_end-time_start)

計算tensor在cpu上的計算速度

time_start=time.time()
dist2 = F.pairwise_distance(c, d, p=2)#pytorch求歐氏距離
time_end=time.time()
print(time_end-time_start)

計算tensor在cuda上的計算速度

time_start=time.time()
dist2 = F.pairwise_distance(e, f, p=2)
time_end=time.time()
print(time_end-time_start)

計算結果: 0.0031995773315429688 0.025923967361450195
0.0006928443908691406 `


管中窺豹,可見一斑,GPU相較與CPU擁有巨大優勢!
但是一下常見的運算函式只能在numpy上執行,不能在tensor上執行,不得不將在GPU上的資料拉回到CPU上。 比如距離的計算公式:

python各類距離公式實現

`

-- coding: utf-8 --

from numpy import *

vector1 = mat([1,2,3])
vector2 = mat([4,5,6])
print (sqrt((vector1-vector2)*((vector1-vector2).T)))

import numpy as np

x = np.random.random(10)
y = np.random.random(10)

solution1

dist1 = np.linalg.norm(x - y)

solution2

dist2 = np.sqrt(np.sum(np.square(x - y)))
print('x', x)
print('y', y)
print('dist1:', dist1)
print('dist2:', dist2)

solution3

from scipy.spatial.distance import pdist

X=np.vstack([x,y]) d2=pdist(X)[0] print('d2:',d2)`

這裡面的函式就會將資料由GPU拉回到CPU。

但是在使用:


import torch.nn.functional as F distance =F.pairwise_distance(rep_a, rep_b, p=2)


此時很有可能遇到這個報錯:

RuntimeError: dimension out of range (expected to be in range of
[-1, 0], but got 1)
變數形狀問題

執行程式碼時,老是報錯:
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
輸出a和b的維度發現: a的形狀為 [20 , 5], 但是b的形狀為[5 , ]。考慮用pytorch中的view函式,改變b的形狀為[5,1]:

`
// b最先的形狀為[5,]: tensor([ 1, 2, 3, 4, 5], device='cuda:0')
// view後b的形狀為[5,1]: tensor([ [1], [2], [3], [4], [5]], device='cuda:0')

b=b.view(len(b),1)
S=a.mm(b)

`
從numpy.array( )的陣列中,取某一行的資料轉換成pytorch變數時,容易出現這個問題。類似地,也可以提前考慮用numpy.reshape( )改變所取的那一行資料,再轉換成pytorch變數,再進行點乘運算。程式碼如下:

`
// b最先的格式為: [1,2,3,4,5]
// reshape後b的格式為: [ [1.] [2.] [3.] [4.] [5.] ]

b = numpy.reshape(b,(len(b),1))
b = Variable(
      torch.from_numpy(b).type(T.FloatTensor))
S=a.mm(b)

`