增加np.array的大小

问题描述

我在形状为(2000、20、28)的X矩阵上运行了conv1D,批量大小为2000、20个时间步长和28个特征。 我想继续使用conv2D CNN,并将矩阵的维数增加到具有10个元素的(2000,20,28,10),我可以为其构建(2000,20,28)X矩阵。同样,我想得到一个大小为(2000,10)的y数组,即用于LSTM和Conv1D网络的大小为(2000,)的y数组的5倍。

我用来根据输入datax,dataY创建20个时间步长的代码

def LSTM_create_dataset(datax,dataY,seq_length,step):
    Xs,ys = [],[]
    for i in range(0,len(datax) - seq_length,step):
        v = datax.iloc[i:(i + seq_length)].values
        Xs.append(v)
        ys.append(dataY.iloc[i + seq_length])
    return np.array(Xs),np.array(ys)

我在准备创建conv2D NN的数据的循环中使用此功能

for ric in rics:
    datax,dataY = get_model_data(dbInput,dbList,ric,horiz,drop_rows,triggerUp1,triggerLoss,triggerUp2 = 0)
    datax = get_model_cleanXset(datax,trigger)                             # Clean X matrix for insufficient data
    Xs,ys = LSTM_create_dataset(datax,step)        # slide over seq_length for a 3D matrix
    Xconv.append(Xs)
    yconv.append(ys)
    Xconv.append(Xs)
    yconv.append(ys)
我获得(10,2000,20,28)Xconv矩阵代替(2000,20,28,10)目标输出矩阵X和(10,2000)矩阵y代替目标(2000,10) )。 我知道我可以很容易地用yconv = np.reshape(yconv,(2000,5))重塑yconv。但是Xconv Xconv = np.reshape(Xconv,20,28,10))的重塑函数似乎很危险,因为我无法虚化输出甚至错误。 我如何安全地进行操作(或者您可以确认我的首次尝试? 提前谢谢。

解决方法

如果您的y矩阵的形状为(2000年10月),那么您将无法将其成形为所需的(2000,5)。我已经在下面演示了这一点。

# create array of same shape as your original y
arr_1 = np.arange(0,2000*10).reshape(10,2000) 
print(arr_1.shape) # returns (10,2000)
arr_1 = arr_1.reshape(2000,5)

这将返回以下错误消息,因为必须保证前后形状的尺寸必须匹配。

ValueError: cannot reshape array of size 20000 into shape (2000,5)  

我不完全理解您无法可视化输出的说法-如果需要,您可以手动检查reshape函数是否正确执行了数据集(或其中的一小部分,以确认该函数有效地工作),使用打印语句,如下所示-通过将输出与原始数据进行比较,然后比较预期的数据。

import numpy as np

arr = np.arange(0,2000) 
arr = arr.reshape(20,10,1) # reshape array to shape (20,1)

# these statements let you examine the array contents at varying depths
print(arr[0][0][0])
print(arr[0][0])