AttributeError:“系列”对象没有属性“标签”

时间:2018-08-01 13:07:25

标签: python neural-network classification mfcc

我正在尝试遵循有关神经网络中声音分类的教程,并且我发现同一教程的3个不同版本,所有版本都可以工作,但是在代码的这一点上它们都遇到了障碍,其中我收到“ AttributeError:'Series'对象没有属性'label'”的问题。我对NN或Python并不是特别满意,所以道歉,如果这是一个琐碎的事情,例如弃用错误,但我似乎无法自己弄清楚。

def parser(row):
   # function to load files and extract features
   file_name = os.path.join(os.path.abspath(data_dir), 'Train/train', str(row.ID) + '.wav')

   # handle exception to check if there isn't a file which is corrupted
   try:
      # here kaiser_fast is a technique used for faster extraction
      X, sample_rate = librosa.load(file_name, res_type='kaiser_fast') 
      # we extract mfcc feature from data
      mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T,axis=0) 
   except Exception as e:
      print("Error encountered while parsing file: ", file)
      return None, None
 
   feature = mfccs
   label = row.Class
 
   return [feature, label]

temp = train.apply(parser, axis=1)
temp.columns = ['feature', 'label']

from sklearn.preprocessing import LabelEncoder

X = np.array(temp.feature.tolist())
y = np.array(temp.label.tolist())

lb = LabelEncoder()

y = np_utils.to_categorical(lb.fit_transform(y))

如前所述,我看过关于同一主题的三个不同的教程,所有教程都以相同的“ temp = train.apply(parser,axis = 1)结尾。temp.columns = ['feature','label' ]”片段,因此我假设这是正确分配的,但不知道它在哪里出错。帮助赞赏!

编辑:按照要求进行追溯,事实证明我添加了错误的追溯。从那以后,我还发现这是将系列对象转换为数据框的情况,因此这方面的任何帮助都会很棒。

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-1613f53e2d98> in <module>()
  1 from sklearn.preprocessing import LabelEncoder
  2 
----> 3 X = np.array(temp.feature.tolist())
  4 y = np.array(temp.label.tolist())
  5 

/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
   4370             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   4371                 return self[name]
-> 4372             return object.__getattribute__(self, name)
   4373 
   4374     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'feature'

1 个答案:

答案 0 :(得分:2)

您当前的parser(row)方法的实现为train DataFrame中的每一行数据返回一个列表。但这然后被收集为pandas.Series对象。

因此,您的temp实际上是一个Series对象。然后以下行没有任何作用:

temp.columns = ['feature', 'label']

由于tempSeries,因此它没有任何列,因此temp.featuretemp.label不存在,因此错误。

如下更改您的parser()方法:

def parser(row):
    ...
    ...
    ...

    # Return pandas.Series instead of List
    return pd.Series([feature, label])

这样做,来自temp = train.apply(parser, axis=1)的apply方法将返回DataFrame,因此您的其他代码将起作用。

我不能说您正在关注的教程。也许他们遵循的是熊猫的旧版本,该版本允许将列表自动转换为DataFrame