Я пытался сделать фильтр шума, интегрированный с искусственным интеллектом. Но при компиляции следующего кода я столкнулся с ошибкой ниже. Как я могу решить эту проблему?
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)
Вывод на терминал:
Traceback (most recent call last):
File "c:\Python\Noise Filter.py", line 81, in
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
Подробнее здесь: https://stackoverflow.com/questions/793 ... ython-code
Как устранить IndexError: индекс кортежа выходит за пределы диапазона для моего кода Python ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
IndexError: индекс списка выходит за пределы диапазона в FAISS.from_documents
Anonymous » » в форуме Python - 0 Ответы
- 72 Просмотры
-
Последнее сообщение Anonymous
-
-
-
IndexError: индекс списка выходит за пределы диапазона в FAISS.from_documents
Anonymous » » в форуме Python - 0 Ответы
- 45 Просмотры
-
Последнее сообщение Anonymous
-
-
-
IndexError: индекс списка выходит за пределы диапазона в потоковом освещении
Anonymous » » в форуме Python - 0 Ответы
- 52 Просмотры
-
Последнее сообщение Anonymous
-