You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

np.array提示数组存在非均匀部分,但无法定位问题原因?

NumPy数组非均匀形状报错排查疑惑

问题背景

运行音频处理代码时,调用np.array(all_X_data)触发如下错误:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (128,182) + inhomogeneous part.

预期all_X_data应是182行128列的矩阵,且认为经librosa.melspectrogram处理后所有元素默认宽度为128,对报错原因感到困惑。

完整代码

#Creating spectrograms
import librosa
import numpy as np

def prepare_audio(audio_path):
  list_matrices = []
  y,sr = librosa.load(audio_path,sr=22050)
  D = np.abs(librosa.stft(y))**2
  S = librosa.feature.melspectrogram(S=D, sr=sr)
  list_matrices.append(S)
  return list_matrices

all_X_data = []
targets = []

#Loading files into spectrogram and putting the result in a matrix 
from pathlib import Path
path = '/Users/xyz/Desktop/Audio_Samplepack'
pathlist = Path(path).glob('**/*.wav')
for path in pathlist:
     path_in_str = str(path)
     audio = prepare_audio(path_in_str)
     all_X_data += audio
     targets += ([0]*len(audio))

#Train_test_split with above data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(np.array(all_X_data), 
                                                    np.array(targets),
                                                    test_size=0.33,
                                                    random_state=42)

排查操作

  1. 逐个检查元素第一维度长度:
for element in all_X_data:
    print(len(element))

结果显示182个元素的长度均为128。

  1. 尝试自动移除不符合长度的元素:
print(len(all_X_data))
for element in all_X_data:
    if len(element) != 128:
        all_X_data.remove(element)    
print(len(all_X_data))

输出结果:

182
182

无元素被移除,说明所有元素第一维度长度都是128,但报错仍提示存在非均匀部分。

核心疑问

非均匀部分到底在哪里?为什么找不到需要移除的元素?

内容的提问来源于stack exchange,提问作者Laulito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:24:50