我正在尝试遵循神经网络中声音分类的教程,并且我发现了同一教程的 3 个不同版本,所有这些版本都有效,但它们在代码中的此时都遇到了障碍,其中我收到“AttributeError:‘Series’对象没有属性‘label’”问题。我对神经网络或 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'
最佳答案
您当前实现的 parser(row)
方法从 train
DataFrame 中返回每行数据的列表。但这随后被收集为 pandas.Series 对象。
所以你的 temp
实际上是一个 Series
对象。然后下面的行没有任何效果:
temp.columns = ['feature', 'label']
由于 temp
是一个 Series
,因此它没有任何列,因此 temp.feature
和 temp.label
不存在,因此出现错误。
更改您的 parser()
方法,如下所示:
def parser(row):
...
...
...
# Return pandas.Series instead of List
return pd.Series([feature, label])
通过执行此操作,temp = train.apply(parser, axis=1)
中的 apply 方法将返回一个 DataFrame
,因此您的其他代码将起作用。
我无法透露您正在遵循的教程。也许他们遵循旧版本的 pandas,它允许列表自动转换为 DataFrame
。
关于python - 属性错误: 'Series' object has no attribute 'label' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51634111/