首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Keras Librosa神经网络音乐分析出错: Scikit导入中变量未知

Python Keras Librosa神经网络音乐分析出错: Scikit导入中变量未知
EN

Stack Overflow用户
提问于 2019-01-27 10:02:23
回答 1查看 56关注 0票数 0

最近,我一直在尝试完成一个实验,在这个实验中,用Keras创建了一个神经网络音乐分析程序,并修改了神经网络中的层数,以找到对性能的影响。我的程序来源是下面的网站:

https://medium.com/@navdeepsingh_2336/identifying-the-genre-of-a-song-with-neural-networks-851db89c42f0

我最近遇到了几个关于我的程序的错误,在另一个关于Stack Overflow的开发人员的建议下,我决定寻求Scikit库部分的帮助。

代码如下所示:

代码语言:javascript
复制
import librosa
import librosa.feature
import librosa.display
import glob
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.utils.np_utils import to_categorical
from sklearn.model_selection import train_test_split,        
StratifiedShuffleSplit, StratifiedKFold



def display_mfcc(song):
    y, _ = librosa.load(song)
    mfcc = librosa.feature.mfcc(y)

    plt.figure(figsize=(10, 4))
    librosa.display.specshow(mfcc, x_axis='time', y_axis='mel')
    plt.colorbar()
    plt.title(song)
    plt.tight_layout()
    plt.show()


def extract_features_song(f):
    y, _ = librosa.load(f)

    mfcc = librosa.feature.mfcc(y)
    mfcc /= np.amax(np.absolute(mfcc))

    return np.ndarray.flatten(mfcc)[:25000]

def generate_features_and_labels():
    all_features = []
    all_labels = []
    genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 
    'jazz', 'metal', 'pop', 'reggae', 'rock']
    for genre in genres:
        sound_files = glob.glob('genres/'+genre+'/*.au')
        print('Processing %d songs in %s genre...' % 
        (len(sound_files), genre))
        for f in sound_files:
            features = extract_features_song(f)
            all_features.append(features)
            all_labels.append(genre)

    label_uniq_ids, label_row_ids = np.unique(all_labels, 
    return_inverse=True)
    label_row_ids = label_row_ids.astype(np.int32, copy=False)
    onehot_labels = to_categorical(label_row_ids,   
    len(label_uniq_ids))
    return np.stack(all_features), onehot_labels


features, labels = generate_features_and_labels()

print(np.shape(features))
print(np.shape(labels))

training_split = 0.8

alldata = np.column_stack((features, labels))
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.20,  
random_state=37)
for train_index, test_index in sss.split(X, y):
  X_train, X_test = X[train_index], X[test_index]
  y_train, y_test = y[train_index], y[test_index]


print(np.shape(train))
print(np.shape(test))

train_input = test[:,:-10]
train_labels = train[:,-10:]

test_input = test[:,:-10]
test_labels = test[:,-10:]

print(np.shape(train_input))
print(np.shape(train_labels))

model = Sequential([
    Dense(100, input_dim=np.shape(train_input)[1]),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
    ])


 model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
print(model.summary())

model.fit(train_input, train_labels, epochs=10, batch_size=32,
          validation_split=0.2) 

loss, acc = model.evaluate(test_input, test_labels, batch_size=32)

print('Done!')
print('Loss: %.4f, accuracy: %.4f' % (loss, acc))

Python开始提供预期的响应,生成:

代码语言:javascript
复制
Processing 100 songs in blues genre...
Processing 100 songs in classical genre...
Processing 100 songs in country genre...
Processing 100 songs in disco genre...
Processing 100 songs in hiphop genre...
Processing 100 songs in jazz genre...
Processing 100 songs in metal genre...
Processing 100 songs in pop genre...
Processing 100 songs in reggae genre...
Processing 100 songs in rock genre...
(1000, 25000)
(1000, 10)

但中断了该过程并显示了以下错误消息:

代码语言:javascript
复制
Traceback (most recent call last):
  File "/Users/surengrigorian/Documents/Stage1.py", line 60, in     <module>
    for train_index, test_index in sss.split(X, y):
NameError: name 'X' is not defined

感谢您在这个问题上所能提供的任何帮助。

EN

回答 1

Stack Overflow用户

发布于 2019-01-27 11:36:48

您的代码中没有定义X和Y,我相信在您的情况下,X等于要素,Y等于标注

代码语言:javascript
复制
X=features
y=labels

for train_index, test_index in sss.split(X, y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

希望能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54384473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档