【问题标题】:Increase the size of a np.array增加 np.array 的大小
【发布时间】:2020-08-12 21:59:46
【问题描述】:

我在形状为 (2000, 20, 28) 的 X 矩阵上运行 conv1D,批量大小为 2000、20 个时间步长和 28 个特征。 我想继续使用 conv2D CNN 并将我的矩阵的维数增加到 (2000, 20, 28, 10) 有 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, dataY, seq_length, 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, (2000, 20, 28, 10)) 的重塑功能似乎很危险,因为我无法将输出可视化,甚至是错误的。 我怎样才能安全地做到这一点(或者你能确认我的第一次尝试吗? 提前非常感谢。

【问题讨论】:

    标签: python numpy tensorflow reshape


    【解决方案1】:

    如果您的 y 矩阵的形状为 (10, 2000),那么您将无法将其调整为所需的 (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,10,1) # reshape array to shape (20, 10, 10, 1)
    
    # these statements let you examine the array contents at varying depths
    print(arr[0][0][0])
    print(arr[0][0])
    

    【讨论】:

    • 确实如此。我的意思是 (2000, 10),这是通过 reshape 实现的...
    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2020-12-02
    • 2015-12-08
    • 2021-01-15
    • 2016-11-08
    • 1970-01-01
    • 2012-06-17
    • 2016-04-23
    相关资源
    最近更新 更多