import KNN
def c(i,d,l,k):
dss=d.shape[0]
dm=tile(i,(dss,1))-d
sqm=dm**2
sqd=sqm.sum(axis=1)
dist=sqd**0.5
sDI=dist.argsort()
clc={}
for i in range(k):
vl=l[sDI[i]]
clc[vl]=clc.get(vl,0)+1
sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
return sCC[0][0]
c([0,0],g,l,3)
Error:
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
c([0,0],g,l,3)
File "<pyshell#31>", line 12, in c
sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
NameError: global name 'operator' is not defined
KNN contains the following code:
from numpy import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
Why is there a error as mentioned above? Program is run on Python 3.3.2. This code is a simple k-classification algorithm run in Python.
You need to import operator
into the local namespace; import KNN
will not also import the submodules it imports.
As a rule, you need to be explicit about any and all modules and objects you use, with the exception of the builtins
(https://docs.python.org/2/library/functions.html).
Unlike some other languages, there are no implicit imports.
Advanced tip/editorial on imports:
You might be tempted to use KNN.operator
. It's available there because it was imported by KNN
. However, this is almost always a regrettable decision, as confuses the picture: Is this a special module? If so what's its interface? Save the cuteness, be explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With