[英]What does "[()]" mean when called upon a numpy array?
I just came across this piece of code:我刚刚遇到了这段代码:
x = np.load(lc_path, allow_pickle=True)[()]
And I've never seen this pattern before: [()]
.我以前从未见过这种模式: [()]
。 What does it do and why is this syntacticly correct?它有什么作用,为什么这在语法上是正确的?
a = np.load(lc_path, allow_pickle=True)
>>> array({'train_ppls': [1158.359413193576, 400.54333992093854, ...],
'val_ppls': [493.0056070137404, 326.53203520368623, ...],
'train_losses': [340.40905952453613, 675.6475067138672, ...],
'val_losses': [217.46258735656738, 438.86770486831665, ...],
'times': [19.488852977752686, 20.147733449935913, ...]}, dtype=object)
So I guess a
is a dict
wrapped in an array for some reason by the person who saved it所以我猜a
是保存它的人出于某种原因包装在数组中的dict
It a way (the only way) of indexing a 0d array:这是索引 0d 数组的一种方式(唯一方式):
In [475]: x=np.array(21)
In [476]: x
Out[476]: array(21)
In [477]: x.shape
Out[477]: ()
In [478]: x[()]
Out[478]: 21
In effect it pulls the element out of the array.实际上,它将元素从数组中拉出。 item()
is another way: item()
是另一种方式:
In [479]: x.item()
Out[479]: 21
In [480]: x.ndim
Out[480]: 0
In在
x = np.load(lc_path, allow_pickle=True)[()]
most likely the np.save
was given a non-array;很可能np.save
被赋予了一个非数组; and wrapped in a 0d object dtype array to save it.并包装在一个 0d 对象 dtype 数组中以保存它。 This is a way of recovering that object.这是恢复该对象的一种方式。
In [481]: np.save('test.npy', {'a':1})
In [482]: x = np.load('test.npy', allow_pickle=True)
In [483]: x
Out[483]: array({'a': 1}, dtype=object)
In [484]: x.ndim
Out[484]: 0
In [485]: x[()]
Out[485]: {'a': 1}
In general when we index a nd array, eg x[1,2]
we are really doing x[(1,2)]
, that is, using a tuple that corresponds to the number of dimensions.一般来说,当我们索引一个 nd 数组时,例如x[1,2]
我们实际上是在做x[(1,2)]
,也就是说,使用对应于维数的元组。 If x
is 0d, the only tuple that works is an empty one, ()
.如果x
是 0d,则唯一有效的元组是空元组()
。
That's indexing the array with a tuple of 0 indices.那是用 0 个索引的元组对数组进行索引。 For most arrays, this just produces a view of the whole array, but for a 0-dimensional array, it extracts the array's single element as a scalar.对于大多数数组,这只会生成整个数组的视图,但对于 0 维数组,它将数组的单个元素提取为标量。
In this case, it looks like someone made the weird choice to dump a non-NumPy object to an array with numpy.save
, resulting in NumPy saving a 0-dimensional array of object
dtype wrapping the original object.在这种情况下,看起来有人做出了奇怪的选择,将非 NumPy 对象转储到numpy.save
数组,导致 NumPy 保存了一个 0 维object
numpy.save
数组,该数组包含原始对象。 The use of allow_pickle=True
and the empty tuple index extracts the object from the 0-dimensional array.使用allow_pickle=True
和空元组索引从 0 维数组中提取对象。
They probably should have picked something other than numpy.save
to save this object.他们可能应该选择numpy.save
以外的其他东西来保存这个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.