2017-04-20 5 views
0

다음 코드에서 모양이 'log_specgrams'입니다 (20,1,12060). 모양을 (20, 60, 201, 1)로 변경하고 싶습니다. 그래서 나는 이와 같은 코드를 작성했습니다.3d 배열을 4 차원 배열로 변경 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에서 발생합니다. 저는 파이썬에 대한 초보자이기 때문에 여러분의 질문을 이해하지 못합니다 (균질?) 더 간단하게 말해 줄 수 있습니까? '균질'이라면 해결책이 있습니까? –

답변

0

모양 변경은 입력 (20,1,12060)이며 원하는 출력 (20, 60, 201, 1) 가정하면 계산 즉, 튜플 누락 치수 자체

+0

답장을 보내 주셔서 감사합니다. 불행히도, 나는 동일한 오류가있었습니다. 다른 의견이 있으십니까? (솔루션?) –

+1

'reshape (-1, 60, 201, 1)'은'None'과 같은 방식으로 작동합니다. –

+1

사실, 최근 numpy (1.11.1)의'None'은'-1'이 예상대로 작동하는 동안 오류를 리턴합니다. –

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)) 

없음 파라미터 소요 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의 축에 대해, 하나의 reshapedata.reshape(20, 60, 201, 1) 또는 @의 YAR의 대답은 똑 바른 앞으로 더있을 수 있습니다. 이 솔루션은 축 크기가 1과 다른 다른 문제로 확장됩니다.

관련 문제