2013-11-02 48 views
1

我正在編寫一個用於查找K Nereast Neighbor的代碼,並且需要使用numPy Python包進行計算。我附上下面的功能代碼:Python導入包函數

#Import packages 
import numpy as np 

def knn(Q,R,k,classvar): 
#Function that does k-NN and selects the k Nearest Neighbours 
#Input parameters 
#Q array of Query points, R array of reference points 
#k is the no of closest points in k-NN 
#classvar is binary class variable either 1 or 0 


#for loop over all Query points 
#calculate distance from ith Query point to all reference points 
     dist = np.apply_along_axis(np.linalg.norm, 1, R-Q) 
#sort distances and find indexes 
     index=np.argsort(dist) 
#pick the kth closest indexes 
     knearest=index[1:k] 
#find the count of 1's and 0's in the binary class variable 
#if count of 1 is more than count of 0 predict class 1 else class 0 
     if sum(e==0) > sum(e==1): 
      preclassQ=0; 
     else: 
      preclassQ=1; 
     return preclassQ 

首先,我想知道,是有必要包含聲明

from numpy import * 
函數定義

,但我們打算給它在IPython中命令行 ?

我救了這個代碼knn.py,然後導入它的命令行和調用的函數如下:

In [58]: import knn 

In [59]: knn.knn(b,a,1,[(0),(0),(1),(1)]) 

但功能不執行,我得到一個錯誤如下:

--------------------------------------------------------------------------- 
NameError         Traceback (most recent call last) 

/Project/<ipython console> in <module>() 

/Project/knn.py in knn(Q, R, k, classvar) 
    14   dist = np.apply_along_axis(np.linalg.norm, 1, R-Q) 
    15 #sort distances and find indexes 

---> 16   index=np.argsort(dist) 
    17 #pick the kth closest indexes 

    18   knearest=index[1:k] 

NameError: global name 'numpy' is not defined 

回答

1

由於您致電np.some_function您不必使用from numpy import *

函數的局部定義必須與全局定義衝突,所以儘量運動import numpy裏面的功能:

def knn(Q, R, k, classvar): 
    import numpy as np 

如果它不工作,什麼地方必須使用numpy.some_function代替np.some_function。 ..

0

之前導入包 'numpy的'

import numpy as np 

你可以定義NP爲g葉形

global np 

代碼將是這樣的

global np 
import numpy as np 

def foo(): 
    np.seterr(divide = 'ignore') 

這個工作對我來說,可能會爲你工作,以及!