gpt4 book ai didi

Python在函数中导入包

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:56 25 4
gpt4 key购买 nike

我正在编写一个寻找K近邻的代码,需要使用numPy 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

最佳答案

由于您正在调用 np.some_function,因此不必使用 from numpy import *

函数的局部定义必须与全局定义冲突,因此请尝试将 import numpy 移至函数内部:

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

如果它不起作用,则必须在某个地方使用 numpy.some_function 而不是 np.some_function...

关于Python在函数中导入包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19737605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com