预期输入有4个维度,但得到了形状为(32,549,1)的数组

2024-10-04 07:33:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用keras测试一个经过训练的cnn模型,但是当我运行代码时,“有一个错误:

expected inputs to have 4 dimensions, but got array with shape (32, 549, 1).

这(32549,1)是我用来训练和测试cnn的对数频谱图的大小,结果很好。除了最后一个错误。你知道吗

我试过了np.rezise公司(-1,amp)和y=(-1,amp)来增加向量,但它不起作用,我真的不知道该怎么办。你知道吗

DIR = 'C:/Users/ROBERTO VILCHEZ/Desktop/Redes/TRAIN/ayuda/ayuda_1.wav'
SAMPLE_RATE = 88200
model=load_model('C:/Users/ROBERTO VILCHEZ/Desktop/Redes/mi_modelo.h5')

def read_wav_file(x):
   _, wav = wavfile.read(x) 
   # Normalize
   wav = wav.astype(np.float32) / np.iinfo(np.int16).max
   return wav

def log_spectrogram(wav):
    freqs, times, spec = stft(wav, SAMPLE_RATE, nperseg = 400, noverlap = 240, nfft = 512, padded = False, boundary = None)
    # Log spectrogram
    amp = np.log(np.abs(spec)+1e-10)

    return freqs, times, amp


threshold_freq=5500

eps=1e-10

x=DIR 

wav = read_wav_file(x)

L = 88200

if len(wav) > L:
    i = np.random.randint(0, len(wav) - L)
    wav = wav[i:(i+L)]  

elif len(wav) < L:
    rem_len = L - len(wav)
    silence_part = np.random.randint(-100,100,88200).astype(np.float32) / 

np.iinfo(np.int16).max
j = np.random.randint(0, rem_len)
silence_part_left  = silence_part[0:j]
silence_part_right = silence_part[j:rem_len]
wav = np.concatenate([silence_part_left, wav, silence_part_right])
freqs, times, spec = stft(wav, L, nperseg = 400, noverlap = 240, nfft = 
512, padded = False, boundary = None)

if threshold_freq is not None:
    spec = spec[freqs <= threshold_freq,:]
    freqs = freqs[freqs <= threshold_freq]

    amp = np.log(np.abs(spec)+eps)

    y = np.expand_dims(amp, axis=3)

    res = model.predict(y)

其余的代码都正常工作,但只有最后一部分告诉我,error期望输入有4个维度,但是得到了一个形状为(32,549,1)的数组。你知道吗

完全错误:

Traceback (most recent call last):
    File "C:\Users\ROBERTO
VILCHEZ\Desktop\Redes\prueba.py", line 76, in <module>
    res = model.predict(y)    File "C:\Users\ROBERTO VILCHEZ\AppData\Roaming\Python\Python36\site-packages\keras\engine\training.py",
line 1149, in predict
    x, _, _ = self._standardize_user_data(x)   File "C:\Users\ROBERTO VILCHEZ\AppData\Roaming\Python\Python36\site-packages\keras\engine\training.py",
line 751, in _standardize_user_data
    exception_prefix='input')    File "C:\Users\ROBERTO VILCHEZ\AppData\Roaming\Python\Python36\site-packages\keras\engine\training_utils.py", line 128, in standardize_input_data
    'with shape ' + str(data_shape))

ValueError:检查输入时出错:预期输入为4 维度,但得到了具有形状的数组(32,549,1)


Tags: thresholdmodellennpuserskerasampfreq
1条回答
网友
1楼 · 发布于 2024-10-04 07:33:02

如果你只想预测一个输入,你需要扩展你的测试数据(批量大小。你知道吗

所以这里如果你的y的形状是(32,549,1),做一个简单的:

y = np.expand_dims(y, axis=0) # y shape = (1, 32, 549, 1)

然后运行你的预测。你知道吗

相关问题 更多 >