简体   繁体   English

numpy 中的两个以下重塑 function 有什么区别?

[英]what is the difference between two following reshape function in numpy?

I am building a neural network.我正在构建一个神经网络。 where I have to flatten my training dataset.我必须展平我的训练数据集。

I have two options.我有两个选择。 1 is: 1是:

train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T

and 2nd one is:第二个是:

 train_x_flatten = train_x_orig.reshape(train_x_orig.shape[1]*train_x_orig.shape[2]*train_x_orig.shape[3], 209)

both gave the same shape but I found difference while computing cost?两者都给出了相同的形状,但我在计算成本时发现了差异? why is that?这是为什么? thank you谢谢你

Your original tensor is of at least rank 4 based on the second example.根据第二个示例,您的原始张量至少为 4 级。 The first example pulls each element, ordered by increasing the right-most index, and inserts the elements into rows the length of the zeroth shape.第一个示例提取每个元素,通过增加最右边的索引进行排序,并将元素插入到第零个形状长度的行中。 Then transposes.然后转置。

The second example again pull elements from by incrementing from the right-most index, ie:第二个示例再次通过从最右边的索引递增来提取元素,即:

element = train_x_orig[0, 0, 0, 0]
new_row.append(element)
element = train_x_orig[0, 0, 0, 1]
new_row.append(element)

but the size of the row is different.但行的大小不同。 It is now the dimension of everything else in the tensor.它现在是张量中其他所有内容的维度。

Here is an example to illustrate.这里有一个例子来说明。

First we create an ordered array and reshape it to rank 4.首先,我们创建一个有序数组并将其重塑为排名 4。

import numpy as np

x = np.arange(36).reshape(3,2,3,2)
x
# returns:
array([[[[ 0,  1],
         [ 2,  3],
         [ 4,  5]],

        [[ 6,  7],
         [ 8,  9],
         [10, 11]]],


       [[[12, 13],
         [14, 15],
         [16, 17]],

        [[18, 19],
         [20, 21],
         [22, 23]]],


       [[[24, 25],
         [26, 27],
         [28, 29]],

        [[30, 31],
         [32, 33],
         [34, 35]]]])

Here is the output of the first example这是第一个例子的output

x.reshape(x.shape[0], -1).T
# returns:
array([[ 0, 12, 24],
       [ 1, 13, 25],
       [ 2, 14, 26],
       [ 3, 15, 27],
       [ 4, 16, 28],
       [ 5, 17, 29],
       [ 6, 18, 30],
       [ 7, 19, 31],
       [ 8, 20, 32],
       [ 9, 21, 33],
       [10, 22, 34],
       [11, 23, 35]])

And here is the second example这是第二个例子

x.reshape(x.shape[1]*x.shape[2]*x.shape[3], -1)
# returns:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17],
       [18, 19, 20],
       [21, 22, 23],
       [24, 25, 26],
       [27, 28, 29],
       [30, 31, 32],
       [33, 34, 35]])

How the elements get reordered is fundamentally different.元素如何重新排序是根本不同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM