簡體   English   中英

將 3d 數組更改為 4d 數組 numpy

[英]Change 3d array to 4d array numpy

從以下代碼中,我得到了形狀為 (20,1,12060) 的“log_specgrams”。 我想將形狀更改為 (20, 60, 201, 1)。 所以我寫了這樣的代碼。

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

Reshape 將參數作為一個元組,即

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

或者

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

None 計算缺失的維度本身

假設輸入是(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的軸, data.reshape(20, 60, 201, 1)或 @yar 的單個reshape答案可能更直接。 該解決方案僅擴展到軸大小不同於1的其他問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM