NameError:未定义全局名称“numpy”

时间:2014-08-11 08:38:24

标签: python numpy

我正在尝试通过收集essentia(一个MIR库)函数来编写一个特征提取器。 流程图如下:单个特征提取,池,PoolAggregator,连接以使用np.concatenate

从poolAggregator形成整个特征列表

该脚本在ipython笔记本下运行良好,即使没有导入numpy。 我只是收集了我从前一阶段获得的数组或浮点数,但错误消息:"NameError: global name 'numpy' is not defined"显示。

我试图将“import numpy as np”放在模块的顶部:

import numpy as np
def featureExtractor(path):

或在函数中:

def featureExtractor(path):
    import numpy as np

或在主文件中的模块之外:

import numpy as np
from featureExtractor import featureExtractor

这些都无法解决,请帮助我。

以下是脚本:

from essentia.standard import *
import essentia

def featureExtractor(path):
    loader = MonoLoader(filename = path)
    x = loader()

    pool = essentia.Pool()
    spectrum = Spectrum()
    w = Windowing(type = 'hann')
    # Create needed objects
    mfcc = MFCC()
    centroid = Centroid()

    for frame in FrameGenerator(x, frameSize = 1024, hopSize = 512):    

        mfcc_bands, mfcc_coeffs = mfcc(spectrum(w(frame))) # output: vector_real
        spec_centroid = centroid(spectrum(w(frame))) # output: real

        pool.add('lowlevel.mfcc', mfcc_coeffs)
        pool.add('lowlevel.centroid', spec_centroid)

    aggrPool = PoolAggregator(defaultStats = [ 'mean', 'var' ])(pool) 
    # calculate mean and var for each feature

    # build a feature vector of type array
    list = ['lowlevel.centroid.mean', 'lowlevel.centroid.var',
            'lowlevel.mfcc.mean', 'lowlevel.mfcc.var']

    feature_vec = []

    for name in list:
        feature = aggrPool[name]
        if type(feature) != float:  # for those type == array
           feature_vec = np.concatenate([feature_vec,feature], axis = 0)
        else: # for those type == float
           feature_vec.append(feature)
    return feature_vec

然后我在主文件中命令:

path = "/~/Downloads/~.wav"
from featureExtractor import featureExtractor
featureExtractor(path)

我收到了错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-109-40b5bbac9b17> in <module>()
      1 from featureExtractor import featureExtractor
      2 
----> 3 featureExtractor(path)

/~/ipython_notebook/featureExtractor.py in featureExtractor(path)
     66         for name in list:
     67                 feature = aggrPool[name]
---> 68         if type(feature) != float:  # for those type == array
     69                 feature_vec = np.concatenate([feature_vec,feature], axis = 0)
     70         else: # for those type == float

NameError: global name 'numpy' is not defined

无论我把命令放在哪里(如上所述),我都得到同样的错误

import numpy as np

1 个答案:

答案 0 :(得分:11)

尝试简单

import numpy

位于文件/~/ipython_notebook/featureExtractor.py

的顶部

您的代码似乎需要numpy而不是np作为模块名称。