2017-04-20 223 views
0

从下面的代码中,我得到了具有形状(20,1,12060)的'log_specgrams'。 我想改变形状为(20,60,201,1)。 所以我写了这样的代码。将3d数组更改为4d array numpy

log_specgrams = np.asarray(log_specgrams).reshape(len(log_specgrams), 60, 201, 1) 

但我给了一个错误:

Traceback (most recent call last): 
    File "D:/for-test.py", line 26, in <module> 
    features = extract_features(parent_dir,sub_dirs) 
    File "D:/for-test.py", line 17, in extract_features 
    log_specgrams = np.asarray(log_specgrams).reshape(len(log_specgrams), 60, 201, 1) 
    File "C:\Users\CHS\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 482, in asarray 
    return array(a, dtype, copy=False, order=order) 
ValueError: could not broadcast input array from shape (12060) into shape (1) 
(1, 12060) 

整个代码:

import glob 
import os 
import librosa 
import numpy as np 

def extract_features(parent_dir, sub_dirs, file_ext="*.wav"): 
     log_specgrams = [] 
     for l, sub_dir in enumerate(sub_dirs): 
       for fn in glob.glob(os.path.join(parent_dir, sub_dir, file_ext)): 
         X_in, sample_rate = librosa.load(fn) 
         melspec = librosa.feature.melspectrogram(y=X_in, sr=sample_rate, n_fft=1024, hop_length=441, n_mels=60) 
         logmel = librosa.logamplitude(melspec) 
         logmel = logmel.T.flatten()[:, np.newaxis].T 
         log_specgrams.append(logmel) 

     print(np.shape(logmel)) 
     log_specgrams = np.asarray(log_specgrams).reshape(len(log_specgrams), 60, 201, 1) 
     print(np.shape(log_specgrams)) 
     A = features 

     return np.array(log_specgrams) 


parent_dir = 'Sound-Data_small' 
sub_dirs= ['fold1','fold2'] 
features = extract_features(parent_dir,sub_dirs) 

我真的想改变 'log_specgrams' 的形状,(20,1,12060)到(20,60,201,1)。

+0

错误似乎发生在'asarray'中,即在您重新塑造之前。也许'log_specgrams'的内容不是同质的? –

+0

做一个简单的'重塑'工作吗?用较小的尺寸进行测试,以便可以看到发生了什么。尺寸“1”尺寸的意义是什么?为什么翻转位置? – hpaulj

+0

是的。错误发生在asarry中。因为我是一个关于Python的初学者,所以我不明白你的问题(同质性?)你能更简单地告诉我吗?如果它是“同质的”,那么是否有解决方案? –

回答

0

整形取参数为元组,即

log_specgrams = np.asarray(log_specgrams).reshape((len(log_specgrams), 60, 201, 1)) 

log_specgrams = np.asarray(log_specgrams).reshape((None, 60, 201, 1)) 

无计算丢失的尺寸本身

+0

谢谢你的回答。不幸的是,我有一个相同的错误。你有其他意见吗? (解决方案?) –

+1

只是一个补充,“重塑(-1,60,201,1)”与“无”相同。 –

+1

事实上,在最近的numpy(1.11.1)中'None'会返回一个错误,而'-1'按预期工作。 –

0

假定输入是(20,1,12060)和期望的输出是(20, 60, 201, 1)1尺寸交换,以下应该工作得很好:

data = np.asarray(log_specgrams) 
data = data.swapaxes(1, 2).reshape(20, 60, 201, 1) 

实施例用随机数据:

>>> data = np.random.randn(20, 1, 12060) 
>>> data.shape 
(20, 1, 12060) 

然后,

>>> data = data.swapaxes(1, 2).reshape(20, 60, 201, 1) 
>>> data.shape 
(20, 60, 201, 1) 

可以注意到的是,操作具有两个分量。第一部分交换第二轴和第三轴,将数据从(20, 1, 12060)转换为(20, 12060, 1)。第二部分将第二轴12060分成尺寸为60 x 201的两个新轴。

它适用于不同尺寸的任意轴,但对于不需要重新排列数据的1轴,或者yar的答案与单个reshape可能会更直接。该解决方案仅适用于轴尺寸不同于1的其他问题。