[Python] How to Resolve IndexError: tuple index out of range for my python code

Discussão em 'Python' iniciado por Stack, Dezembro 22, 2024.

  1. Stack

    Stack Membro Participativo

    In the scope of my projects, i've been trying to make noise filter integrated with Artifical Intelligence. But when compiled the following code, i encountered the results that i specify it below my code. How can i resolve it? Anyone help me?

    import librosa
    import librosa.display
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.models import Sequential
    from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Reshape, Input
    from sklearn.model_selection import train_test_split
    from scipy.io.wavfile import write

    # MFCC özelliklerini çıkarma fonksiyonu
    def extract_mfcc(audio, sample_rate, n_mfcc=20, n_fft=2048, hop_length=512):
    mfcc = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=n_mfcc, n_fft=n_fft, hop_length=hop_length)
    return mfcc.T # Zaman eksenine uygun hale getir

    # CNN modeli oluşturma
    def create_cnn_model(input_shape):
    model = Sequential([
    Input(shape=input_shape),
    Conv2D(32, (3, 3), activation='relu', padding="same"),
    BatchNormalization(),
    MaxPooling2D((2, 2), padding="same"),
    Conv2D(64, (3, 3), activation='relu', padding="same"),
    BatchNormalization(),
    MaxPooling2D((2, 2), padding="same"),
    Flatten(),
    Dense(128, activation='relu'),
    BatchNormalization(),
    Dense(np.prod(input_shape[:-1]), activation='linear'),
    Reshape(input_shape[:-1]) # Çıkışı orijinal şekle döndür
    ])
    model.compile(optimizer='adam', loss='mse', metrics=['mse'])
    return model

    # Gürültüsüz ve gürültülü ses dosyalarını yükle
    clean_file_path = "denoised.wav"
    noisy_file_path = "CPLT_140knt.wav"

    clean_audio, sample_rate_clean = librosa.load(clean_file_path, sr=None)
    noisy_audio, sample_rate_noisy = librosa.load(noisy_file_path, sr=None)

    # Uzunlukları eşitle
    min_length = min(len(clean_audio), len(noisy_audio))
    clean_audio = clean_audio[:min_length]
    noisy_audio = noisy_audio[:min_length]

    # MFCC çıkarma
    clean_mfcc = extract_mfcc(clean_audio, sample_rate_clean)
    noisy_mfcc = extract_mfcc(noisy_audio, sample_rate_noisy)

    # Veri seti oluşturma
    X = np.expand_dims(noisy_mfcc, axis=-1) # Gürültülü MFCC
    y = np.expand_dims(clean_mfcc, axis=-1) # Gürültüsüz MFCC

    # Eğitim ve test veri setlerini ayırma
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # CNN giriş boyutunu belirleme
    _, height, width = X_train.shape
    channels = 1
    input_shape = (height, width, channels)

    # CNN modeli oluşturma
    model = create_cnn_model(input_shape)

    # Modeli eğitme
    print("Model eğitiliyor...")
    model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=250, batch_size=128, verbose=1)

    # Gürültüyü temizleme
    predicted_mfcc = model.predict(X_test)

    # MFCC'den ses sinyalini yeniden oluşturma
    def reconstruct_audio_from_mfcc(mfcc, sr, n_fft=2048, hop_length=512):
    mel_spec = librosa.feature.inverse.mfcc_to_mel(mfcc.T)
    mel_spec = np.maximum(mel_spec, 1e-10) # Negatif veya sıfır değerleri önlemek için küçük bir minimum belirle
    # Mel-spektrogramdan ses sinyali oluşturma
    reconstructed_audio = librosa.feature.inverse.mel_to_audio(mel_spec, sr=sr, n_fft=n_fft, hop_length=hop_length)
    return reconstructed_audio

    # İlk test örneğini yeniden oluştur
    reconstructed_audio = reconstruct_audio_from_mfcc(predicted_mfcc[0, ..., 0], sample_rate_clean)

    # Sonuçları görselleştirme
    plt.figure(figsize=(15, 5))
    plt.subplot(3, 1, 1)
    librosa.display.waveshow(noisy_audio, sr=sample_rate_noisy)
    plt.title("Gürültülü Ses")
    plt.subplot(3, 1, 2)
    librosa.display.waveshow(clean_audio, sr=sample_rate_clean)
    plt.title("Gürültüsüz Referans Ses")
    plt.subplot(3, 1, 3)
    librosa.display.waveshow(reconstructed_audio, sr=sample_rate_clean)
    plt.title("CNN ile Temizlenmiş Ses")
    plt.tight_layout()
    plt.show()

    # Temizlenmiş sesi kaydetme
    output_file = "cnn_denoised_audio.wav"
    write(output_file, sample_rate_clean, (reconstructed_audio * 32767).astype(np.int16))
    print(f"CNN ile temizlenmiş ses '{output_file}' olarak kaydedildi.")


    Terminal Output:

    Traceback (most recent call last):
    File "c:\Python\Noise Filter.py", line 81, in <module>
    reconstructed_audio = reconstruct_audio_from_mfcc(predicted_mfcc[0, ..., 0], sample_rate_clean)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "c:\Python\Noise Filter.py", line 74, in reconstruct_audio_from_mfcc
    mel_spec = librosa.feature.inverse.mfcc_to_mel(mfcc.T)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\atabe\AppData\Local\Programs\Python\Python312\Lib\site-packages\librosa\feature\inverse.py", line 278, in mfcc_to_mel
    logmel = scipy.fftpack.idct(mfcc, axis=-2, type=dct_type, norm=norm, n=n_mels)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\atabe\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy\fftpack\_realtransforms.py", line 440, in idct
    return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\atabe\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy\fft\_pocketfft\realtransforms.py", line 31, in _r2r
    tmp, copied = _fix_shape_1d(tmp, n, axis)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\atabe\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy\fft\_pocketfft\helper.py", line 149, in _fix_shape_1d
    return _fix_shape(x, (n,), (axis,))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\atabe\AppData\Local\Programs\Python\Python312\Lib\site-packages\scipy\fft\_pocketfft\helper.py", line 124, in _fix_shape
    if x.shape[ax] >= n:
    ~~~~~~~^^^^
    IndexError: tuple index out of range


    I expects to get resolved issues that i specified :)

    Continue reading...

Compartilhe esta Página