首页 > 解决方案 > AttributeError:“系列”对象没有属性“标签”

问题描述

我正在尝试遵循有关神经网络中声音分类的教程,并且我发现了同一教程的 3 个不同版本,所有这些版本都有效,但它们都在代码中的这一点上遇到了障碍,我得到了“AttributeError:‘系列’对象没有属性‘标签’”问题。我对NNs或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'

标签: pythonneural-networkclassificationmfcc

解决方案


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

所以你temp实际上是一个Series对象。然后以下行没有任何效果:

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

由于temp是 a Series,它没有任何列,因此temp.featureandtemp.label不存在,因此错误。

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

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

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

通过这样做,应用方法 fromtemp = train.apply(parser, axis=1)将返回 a DataFrame,因此您的其他代码将起作用。

我不能说你正在遵循的教程。也许他们遵循了旧版本的 pandas,它允许将列表自动转换为DataFrame.


推荐阅读