我的数组如下
samples_data = [array([0., 0., 0., ..., 0., 0., 0.], dtype=float32)
array([ 0. , 0. , 0. , ..., -0.00020519,
-0.00019427, -0.00107348], dtype=float32)
array([ 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, ...,
-8.9004419e-07, 7.3998461e-07, -6.9706215e-07], dtype=float32)
array([0., 0., 0., ..., 0., 0., 0.], dtype=float32)]
我有一个类似的功能
def generate_segmented_data_1(
samples_data: np.ndarray, sampling_rate: int = 16000
) -> np.ndarray:
new_data = []
for data in samples_data:
segments = segment_audio(data, sampling_rate=sampling_rate)
new_data.append(segments)
new_data = np.array(new_data)
return np.concatenate(new_data)
它显示类似的错误
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 11 has 2 dimension(s)
索引0处的数组类似于
[array([ 0. , 0. , 0. , ..., -0.00022057,
0.00013752, -0.00114789], dtype=float32)
array([-4.3174211e-04, -5.4488028e-04, -1.1238289e-03, ...,
8.4724619e-05, 3.0450989e-05, -3.9514929e-05], dtype=float32)]
那么索引11处的数组类似于这个
[[3.0856067e-05 3.0295929e-05 3.0955063e-05 ... 8.5010566e-03
1.3315652e-02 1.5698154e-02]]
然后我应该怎么做才能将我生成的所有段连接为段的数组?
我不太确定我是否理解你的意图。
b = np.array([[2]])
b.shape
# (1,1)
b = np.array([2])
b.shape
# (1,)
对于问题的分段部分,尚不清楚您的数据结构是什么,但代码示例已损坏,因为您正在附加到一个尚未创建的列表中。
如何使下面数组的形状为1D而不是2D?
b = np.array([[2]]) b_shape = b.shape
这将产生(1,1(。但是,我希望它的结果(1,(不平坦?
我怀疑混淆源于您选择了一个也可以被视为标量的示例,所以我将使用另一个示例:
b = np.array([[1,2]])
现在b.shape
是(1,2)
。去除第一个";一个";维度以任何方式(无论是b.flatten()
、b.squeeze()
还是使用b[0]
(都会产生相同的结果:
assert (b.flatten() == b.squeeze()).all()
assert (b.flatten() == b[0]).all()
现在,对于真正的问题:看起来你正试图连接";行";从";段";,但是";分段";(我相信从你的样本数据来看,这是np.array
的列表?(是不一致的。
您的样本数据非常混乱:段0-10似乎是1D阵列的列表;段11、18和19是2D阵列或浮动列表的列表。这一点,再加上错误代码,表明分段的数据处理存在问题。
现在,要实际连接这两种类型的数据:
new_data = []
for data in samples_data:
segments = function_a(data) # it appears this doesn't return consistent data
segments = np.asarray(segments) # force it to always be an array...
if segments.ndim > 1: # ...and append each row
for row in segments:
new_data.append(row)
elif segments.ndim == 1: # if just one row, append it directly
new_data.append(segments)
else:
# function_a returned an empty list, do nothing
pass
给定显示的数据和代码,这个应该可以工作(但它既没有效率,也没有经过测试(。