繁体   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