python - 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'
解决方案
您当前的方法实现为DataFrameparser(row)
中的每一行数据返回一个列表。train
但这随后被收集为 pandas.Series 对象。
所以你temp
实际上是一个Series
对象。然后以下行没有任何效果:
temp.columns = ['feature', 'label']
由于temp
是 a Series
,它没有任何列,因此temp.feature
andtemp.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
.
推荐阅读
- python-3.x - 为什么在使用 pip 安装软件包时出现无效语法错误
- angular - 为什么不应该在 Angular 组件的构造函数中进行数据初始化?
- numbers - 从数论中寻找原根的算法
- sql - 在 sql 表条目中查找重复单词
- javascript - 从表中删除行时如何更改计算
- android - Android中的平滑擦洗视频
- vba - 表单字段上的 MS Access VBA 代码具有多个 If 以根据输入的值阻止/允许输入
- sql - 使用 spark 从 oracle 读取数据时出错
- sas - SAS - 使用输入将现有字符变量值更改为数字
- java - 在java中暂停一个ExecutorService