前提・実現したいこと
Pythonで機械学習の教師あり学習のアルゴリズムの一つである「最近傍法」を実装してみました。最近傍法のアルゴリズムで距離計算がありますが、この計算をできるだけ省略したいと考えています。
考えてみた事柄
後述するプログラムの中で、
python
1d[t]=np.sum((datT[n,:]-datL[t,:])**2)
を、
python
1for n in range(NL): 2 datL2[n]=np.sum(datL[n,:]**2) 3 4for n in range(count): 5 for t in range(NL): 6 d[t]=np.sum(-2*(datT[n,:]@datL[t,:]))+datL2[t]
のように変えてみました。しかし、まだ省略の余地があると思われるので省略できそうなことを教えて欲しいです。
該当のソースコード
python
1import numpy as np 2import cv2 3NL = 700 4t=0 5imgshape = (120, 100, 3) 6D = np.prod(imgshape) 7datL = np.empty((NL, D)) 8datT = np.empty((NL, D)) 9labL = np.empty(NL, dtype=int) 10labT = np.empty(NL, dtype=int) 11K = 3 12with open ('L.txt') as f: #学習データの読み込み 13 for line in f: 14 line = line.strip() 15 i, s = line.split() 16 img= cv2.imread('sjs-cfw/'+i) 17 vec = img.reshape(-1) 18 datL[t,:]=vec 19 labL[t]=s 20 t=t+1 21 22count=0 23with open ('T.txt') as x: #テストデータの読み込み 24 for line in x: 25 line = line.strip() 26 i, s = line.split() 27 img= cv2.imread('sjs-cfw/'+i) 28 vec = img.reshape(-1) 29 datT[count,:]=vec 30 labT[count]=s 31 count=count+1 32 33d=np.empty((NL,)) 34cnt = 0 35n=0 36datL2=np.empty((NL,)) 37for n in range(NL): 38 datL2[n]=np.sum(datL[n,:]**2) #学習データの計算のさぼり 39 40for n in range(count): 41 for t in range(NL): 42 d[t]=np.sum((datT[n,:]-datL[t,:])**2) 43 #d[t]=np.sum(-2*(datT[n,:]@datL[t,:]))+datL2[t](※) 44 no=d.argmin() 45 if labT[n]==labL[no]: 46 cnt=cnt+1 47 48print(cnt) 49print(cnt/count)
あなたの回答
tips
プレビュー