比方说,我有一个数组,
x.shape = (10,1024)
当我尝试打印x.shape时
x[0].shape它打印1024
当我打印x.shape时
x.shape[0]它打印10
我知道这是一个愚蠢的问题,也许还有其他类似的问题,但有人能给我解释一下吗?
发布于 2018-01-07 13:31:50
x是2D阵列,其也可以被视为具有10行和1024列的1D阵列的阵列。x[0]是第一个有1024个元素的一维子数组(在x中有10个这样的一维子数组),x[0].shape给出了该子数组的形状,恰好是一个1元组(1024, )。
另一方面,x.shape是一个2元组,它表示x的形状,在本例中是(10, 1024)。x.shape[0]提供了元组中的第一个元素,即10。
这是一个带有一些较小数字的演示,希望它更容易理解。
x = np.arange(36).reshape(-1, 9)
x
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]])
x[0]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
x[0].shape
(9,)
x.shape
(4, 9)
x.shape[0]
4发布于 2018-09-22 10:07:04
x[0].shape将给出数组的第一行的长度。x.shape[0]将给出数组中的行数。在你的例子中,它会输出10。如果你输入x.shape[1],它会打印出列数,即1024。如果你输入x.shape[2],它会给出一个错误,因为我们正在处理一个二维数组,并且我们已经超出了索引。让我用一个简单的例子来解释一下'shape‘的所有用法,取一个3x4维的二维零数组。
import numpy as np
#This will create a 2-d array of zeroes of dimensions 3x4
x = np.zeros((3,4))
print(x)
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
#This will print the First Row of the 2-d array
x[0]
array([ 0., 0., 0., 0.])
#This will Give the Length of 1st row
x[0].shape
(4,)
#This will Give the Length of 2nd row, verified that length of row is showing same
x[1].shape
(4,)
#This will give the dimension of 2-d Array
x.shape
(3, 4)
# This will give the number of rows is 2-d array
x.shape[0]
3
# This will give the number of columns is 2-d array
x.shape[1]
3
# This will give the number of columns is 2-d array
x.shape[1]
4
# This will give an error as we have a 2-d array and we are asking value for an index
out of range
x.shape[2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-20-4b202d084bc7> in <module>()
----> 1 x.shape[2]
IndexError: tuple index out of range发布于 2018-01-07 13:33:56
x[0].shape给出了第一行的长度。x.shape[0]给出了“x”维度的第一个分量,即1024行乘10列。
https://stackoverflow.com/questions/48134598
复制相似问题